简体   繁体   中英

How can I map data in rows into one row such that each column is a unique value in SQL

I'm quite a rookie with SQL at the moment but am hoping you can help me map values correctly. The best way I can explain is through a diagram.

What I have: a table with rows and columns linked by a ID with values in each row as per the screenshot below:

我有的

What I need is to condense this in a row as follows:

在此处输入图片说明

Is there a way I can write a script/query that would allow me to do this? Sorry, but I don't really have any idea how to go about this at this point. What I can think of is to run this on a different program, but suspect that this can be done in SQL. Still learning so please excuse my ignorance

This suggests me to do conditional aggregation :

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;

Just in case your [Unique ID] 's are not sequential, consider the following:

Example

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

Returns

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM