Pivot the table

一曲冷凌霜 提交于 2019-12-11 15:26:36

问题


Id Year Values
1 2014 10
1 2015 4
1 2016 7
1 2017 17
2 2014 5
2 2015 6
2 2016 7
2 2017 9

Answer should be

Id 2014 2015 2016 2017
----------------------
1    10    4    7   17
2     5    6    7    9

I tried as below

Select * 
from crosstab(select id,value,year from table)
As res(id int,year int,year int,year int,year int,year int);

回答1:


Another option than using crosstab() would be using GROUP BY and some aggregate function like MAX() with CASE END to pivot.
As extra bonus this is ANSI SQL so it will run in most RDBMS systems.

SELECT 
   Id
 , MAX(CASE WHEN <table>.Year = 2014 WHEN <table>.Values ELSE 0 END) AS 2014
 , MAX(CASE WHEN <table>.Year = 2015 WHEN <table>.Values ELSE 0 END) AS 2015 
 ...
 ...
FROM 
 <table>
GROUP BY 
 <table>.Id


来源:https://stackoverflow.com/questions/54536015/pivot-the-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!