如何将行中的数据映射到一行,以使每一列在SQL中都是唯一的值

时间:2018-10-15 16:39:43

标签: sql sql-server tsql

目前我是SQL的新手,但希望您能帮助我正确映射值。我能解释的最好方法是通过图表。

我所拥有的:一张表格,其中的行和列通过ID链接,每行中的值均如下图所示:

What I have

我需要按如下所示将其压缩为一行:

enter image description here

有没有一种方法可以编写允许执行此操作的脚本/查询?抱歉,目前我真的不知道该如何处理。我能想到的是在另一个程序上运行它,但是怀疑这可以在SQL中完成。还在学习,请原谅我的无知

2 个答案:

答案 0 :(得分:1)

这建议我进行条件聚合:

select id, 
       max(case when UniqueId = 1 then 1 end) as UniqueId1,
       max(case when UniqueId = 2 then 2 end) as UniqueId2,
       max(case when UniqueId = 3 then 3 end) as UniqueId3,
       max(case when UniqueId = 1 then column1 end) as UniqueId1Col1,
       max(case when UniqueId = 2 then column1 end) as UniqueId2Col1,
       max(case when UniqueId = 3 then column1 end) as UniqueId3Col1,
       max(case when UniqueId = 1 then column2 end) as UniqueId1Col2,
       max(case when UniqueId = 2 then column2 end) as UniqueId2Col2,
       max(case when UniqueId = 3 then column2 end) as UniqueId3Col2
from table t
group by id;

答案 1 :(得分:0)

只要您的[Unique ID]不连续,请考虑以下事项:

示例

Select *
 From  (
        Select A.ID
              ,Col = concat('ID',Dense_Rank() over (partition by ID order by  [Unique ID] ),' ',B.Item)
              ,Value = B.Value
         From  YourTable A
         Cross Apply ( values ('Unique' ,concat('',[Unique ID]))
                             ,('Column1',Column1)
                             ,('Column2',Column2)
                     ) B(Item,Value)
       ) src 
 Pivot (max(Value) for Col in ( [ID1 Unique] ,[ID2 Unique] ,[ID3 Unique] ,[ID4 Unique]   -- Expand as necessary
                               ,[ID1 Column1],[ID2 Column1],[ID3 Column1],[ID4 Column1]  -- Expand as necessary
                               ,[ID1 Column2],[ID2 Column2],[ID3 Column2],[ID4 Column2]  -- Expand as necessary
                              )) pvt

返回

enter image description here