工作中有需求要將如下結構的數據(為方便處理數據類型均為字符換):
ID | DATE | VALUE |
a | 2016-10-01 | 1 |
a | 2016-10-02 | 2 |
a | 2016-10-03 | 3 |
b | 2016-10-01 | 3 |
b | 2016-10-02 | 2 |
b | 2016-10-03 | 1 |
合並為如下樣式:
ID | V1 | V2 | V3 |
a | 1 | 2 | 3 |
b | 3 | 2 | 1 |
SQL如下:
select t.id,
max(case(t.date) when '2016-10-01' then t.value end) as v1,
max(case(t.date) when '2016-10-02' then t.value end) as v2,
max(case(t.date) when '2016-10-03' then t.value end) as v3
from table t
group by t.id;
----------------------------------------------------------------------
執行結果很完美!!!