将多行转换为列

时间:2017-06-20 05:02:14

标签: mysql database

我想将行更改为列。这就是我现在所拥有的:

NAME      | YEAR | INCOME  | EXPENSE
COMPANY-1 | 2017 | €30000  | €15000
COMPANY-1 | 2016 | €50000  | €10000
COMPANY-2 | 2017 | €20000  | €5000
COMPANY-2 | 2016 | €80000  | €95000

这就是我想要的:

NAME      | INCOME_2017  | EXPENSE_2017 | INCOME_2016  | EXPENSE_2016
COMPANY-1 | €30000       | €15000       | €50000       | €10000
COMPANY-2 | €20000       | €5000        | €80000       | €95000

有人知道我该怎么做吗?我复制了很多PIVOT脚本。但那不起作用......

1 个答案:

答案 0 :(得分:1)

您可以尝试使用此sql来获得所需的结果。

1)使用CASE获取所需的列。

2)使用最大条件获得最大值。

SELECT  `name` ,
 MAX( CASE WHEN  `year` =2017 THEN  `income` ELSE 0 END ) AS INCOME_2017,
 MAX( CASE WHEN  `year` =2017 THEN  `expense` ELSE 0 END ) AS EXPENSE_2017,
 MAX( CASE WHEN  `year` =2016 THEN  `income` ELSE 0 END ) AS INCOME_2016,
 MAX( CASE WHEN  `year` =2016  THEN  `expense` ELSE 0 END ) AS EXPENSE_2016
 FROM  `test_data` GROUP BY  `name`