Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

sql - PIVOT with MONTH()

How can I pivot for a column with dates as month?

Example:

Data:

|-----------------------------------|
| def_kstnr | def_zeit | def_datum  |
|-----------------------------------|
| 100       | 3.2      | 2011-11-02 |
| 110       | 2.8      | 2011-02-03 |
| 120       | 5.4      | 2011-11-04 |
| 130       | 2.4      | 2011-08-05 |
| 140       | 4.9      | 2011-09-06 |
| 150       | 1.5      | 2011-10-07 |
| 160       | 2.6      | 2011-12-08 |
|-----------------------------------|

Query:

SELECT
    def_kstnr,
    [1] AS Jan,
    [2] AS Feb,
    [3] AS Mrz,
    [4] AS Apr,
    [5] AS Mai,
    [6] AS Jun,
    [7] AS Jul,
    [8] AS Aug,
    [9] AS Sep,
    [10] AS Okt,
    [11] AS Nov,
    [12] AS Dez
FROM
    dbo.def
PIVOT
(
    SUM(def_zeit)
    FOR MONTH(def_datum)
    IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
) AS pvtMonth
GROUP BY
    dbo.def.def_kstnr,
    MONTH(def_datum)

I get this error:

Incorrect syntax near '('.

(Line with "FOR MONTH(def_datum)")

Result should look like this:

|-----------------------------------------------------------------------------------|
| def_kstnr | Jan | Feb | Mrz | Apr | Mai | Jun | Jul | Aug | Sep | Okt | Nov | Dez |
|-----------------------------------------------------------------------------------|
| 100       |     |     |     |     |     |     |     |     |     |     | 3.2 |     |
| 110       |     | 2.8 |     |     |     |     |     |     |     |     |     |     |
...
|-----------------------------------------------------------------------------------|

Thank you :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you move the Month function into a prior sourcetable the PIVOT works. Note I don't think you need to go grouping things following the pivot.

SELECT
    def_kstnr,
    [1] AS Jan,
    [2] AS Feb,
    [3] AS Mrz,
    [4] AS Apr,
    [5] AS Mai,
    [6] AS Jun,
    [7] AS Jul,
    [8] AS Aug,
    [9] AS Sep,
    [10] AS Okt,
    [11] AS Nov,
    [12] AS Dez
FROM
(Select 
def_kstnr,
def_zeit,
 MONTH(def_datum) as TMonth
  from
    dbo.def) source
PIVOT
(
    SUM(def_zeit)
    FOR TMonth
    IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
) AS pvtMonth

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...