2017-06-20 179 views
1

我想將我的行更改爲列。這是我現在有:將多行轉換爲列

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

你可以試試這個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` 
+1

它的工作原理!謝謝! – Mooelb