问题
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