首页 > 解决方案 > 多行值合二为一,用于重复值

问题描述

如果 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      

标签: sqlsql-serversql-server-2008

解决方案


您可以使用条件聚合:

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;

推荐阅读