sql - 多行值合二为一,用于重复值
问题描述
如果 ID 重复,我必须将 C(第 1 行)的值移到第 1 列,将 D(第 1 行)的
值移到第 2 列,将 C(第 2 行)的值移到第 3 列,将 D(第 2 行)的值移到第4列,C(第3行)的值到第5列和D(第3行)的值到第6列,有没有办法在sql中做到这一点
谢谢你
ID B C D 1 2 3 4 5 6
1 Hat Device1 34
2 Mat Device2 65
3 Cat Device3 76
3 Sat Device4 34
3 Hat Device5 89
4 Hat Device6 23
4 Hat Device7 12
ID B 1 2 3 4 5 6
1 Hat Device1 34
2 Mat Device2 65
3 Cat Device3 76 Device4 34 Device5 89
4 Hat Device6 23
解决方案
您可以使用条件聚合:
select id, min(b) as b,
max(case when seqnum = 1 then c end) as [1],
max(case when seqnum = 1 then d end) as [2],
max(case when seqnum = 2 then c end) as [3],
max(case when seqnum = 2 then d end) as [4],
max(case when seqnum = 3 then c end) as [5],
max(case when seqnum = 3 then d end) as [6]
from (select t.*, row_number() over (partition by id order by id) as seqnum
from t
) t
group by id;
推荐阅读
- javascript - 如何在 localStorage 中不断更新数据?
- javascript - 从远程托管页面访问 soket.io 服务器 - 需要未定义
- javascript - 使用 Bing Image API Javascript 搜索图像
- python - python替换数据框熊猫中所有列的多个值
- sql - 当 Rows 对应于其他列中的 MAX 时保持 NULL
- firebase - 我可以使用不同的参数并行运行自定义菜单中的谷歌应用程序脚本功能吗?
- javascript - FIrebase 应用程序未在 Vue3-Ionic 项目上初始化
- javascript - 检查 JS 远程替换、Shopify 中的变体可用性
- docker - 仅在发布阶段指定环境变量
- python - 从Python中的稀疏矩阵开始获取图形中路径/行走数量的有效方法