从列中填充日期作为列名

时间:2019-01-24 09:30:20

标签: sql pivot

形成以下数据集:

Column A | Column B | Column C

Monkey   | 201901   | 100

Donkey   | 201901   | 100

Banana   | 201901   | 100

Monkey   | 201902   | 100

Donkey   | 201902   | 100

Banana   | 201902   | 100

Monkey   | 201903   | 100

Donkey   | 201903   | 100

Banana   | 201903   | 100

Monkey   | 201904   | 100

Donkey   | 201904   | 100

Banana   | 201904   | 100

我想要这样的输出:

Animals | 201901 | 201902 | 201903 | 201904

Monkey  | 100    | 100    | 100    | 100    
Donkey  | 100    | 100    | 100    | 100    
Banana  | 100    | 100    | 100    | 100   

2 个答案:

答案 0 :(得分:0)

您要有条件的聚合:

SELECT colA AS Animals, 
       MAX(CASE WHEN colB = '201901' THEN colC END) AS 201901,
       MAX(CASE WHEN colB = '201902' THEN colC END) AS 201902,
       MAX(CASE WHEN colB = '201903' THEN colC END) AS 201903,
       . . . 
       MAX(CASE WHEN colB = '202012' THEN colC END) AS 202012
FROM table t
GROUP BY colA;

答案 1 :(得分:0)

您可以使用数据透视

select cola, max([201901]) as [201901], max([201902]) as [201902],max([201903]) as [201903], max([201904]) as [201904]
from tablename
pivot
(max(col3) for col2 in ([201901],[201902],[201903],[201904])
)pv
group by cola