首页 > 解决方案 > 对多列进行透视查询

问题描述

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

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

标签: sql

解决方案


您可以使用条件聚合:

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;

推荐阅读