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
解决方案
您可以使用条件聚合:
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;
推荐阅读
- material-ui - 任何类似于 bootswatch 的 material-ui 简单/基本主题集合?
- json - 访问嵌套元素
- google-bigquery - 为什么 biguery.tables.list 和 bigquery.tables.get 权限不属于“所有者”角色?
- r - For循环在多个目录中进行图像采样
- python - 给定一个数字 N,交换其中的两个半字节并找到结果数字
- python - 如何使用精灵组和杀死精灵组
- google-cloud-platform - 服务帐户无法将项目附加到共享 VPC
- r - 重塑表格:通过每年重复多个列来扩大表格
- java - 在一行上打印多行 int 值作为分隔字符串
- arrays - 用于 jQuery 数据表的 PowerShell DB2 数据表行到 JSON 文件