sql - How to use pivot in SQL?
问题描述
I have a table that looks like below:
Need to convert the same into the below format:
The data is at A,B, C level. Tried using case when as shown below but it is resulting in multiple rows. So thinking of using a pivot.
Select a,b,c,
case when D = N and E = 1 then N1 = value,
case when D = N and E = 2 then N2 = value,
case when D = O and E = 1 then O1 = value,
case when D = O and E = 2 then O2 = value,
Any help would be appreciated. Thank you!
解决方案
Use aggregation:
Select a, b, c,
max(case when D = 'N' and E = 1 then value end) as N1,
max(case when D = 'N' and E = 2 then value end) as N2,
max(case when D = 'O' and E = 1 then value end) as O1,
max(case when D = 'O' and E = 2 then value end) as O2
from t
group by a, b, c;
Note that this also fixes the logic in the case
expressions.
推荐阅读
- python - 空调度器,用scrapy中的URL重新填充调度器
- arm - ARM Cortex M 检测调试器是处于运行模式还是调试模式
- ms-office - Office 插件 - 从 Excel 中启动 Word
- apache-spark - HIVE:插入查询失败并出现错误“java.lang.OutOfMemoryError:超出 GC 开销限制”
- python - 有没有办法在 Flask 中的 redirect() 之后从函数返回一个值?
- jmeter - 我想使用 Jmeter 脚本启动和停止 localhost 服务器(远程机器)
- android - 应用程序关闭时在后台播放视频声音(在通知栏中),就像 VLC 播放器一样
- c# - 无法使用 Sqlite 和 entityFramework (FileNotFoundException / SQLitePCLRaw.batteries_v2)
- python - 光学并行度
- javascript - 如何在 DHTMLX 甘特图中过滤多个部门