在多列上进行数据透视查询

时间:2019-10-27 11:47:50

标签: sql

我想在下表中编写数据透视查询。 本质上,我希望输出看起来像这样

col1 col2       HDL  LDL CDL MDL
111  2018-12-21 110  23  21  212
111  2018-12-22 212  4312    21
... and so on

col 1和col 2的组合是唯一的

col1 col2       col3 col4
111 2018-12-21  HDL 110
111 2018-12-21  LDL 23
111 2018-12-21  CDL 21
111 2018-12-21  MDL 212

111 2018-12-22  MDL 21
111 2018-12-22  HDL 212
111 2018-12-22  LDL 4312

333 2018-12-22  HDL 112
444 2018-12-22  PPP 00112

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合:

select col1, col2, 
       max(case when col3 = 'HDL' then col4 end) as HDL,
       max(case when col3 = 'LDL' then col4 end) as LDL,
       max(case when col3 = 'CDL' then col4 end) as CDL,
       max(case when col3 = 'MDL' then col4 end) as MDL
from t
group by col1, col2;
相关问题