gpt4 book ai didi

mysql - 将多行转换为列

转载 作者:搜寻专家 更新时间:2023-10-30 23:34:39 25 4
gpt4 key购买 nike

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

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 脚本。但这没有用...

最佳答案

您可以尝试此 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`

关于mysql - 将多行转换为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44644177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com