Home > Software design >  Group information at many rows but the same column to the one row
Group information at many rows but the same column to the one row

Time:04-20

Can you help me with this problem? I have a one table which records measuring data with information related to the ParentID. Unfortunately, each measuring data are written into one column (identified by value of previous columns). I would like to read all values from this column and write it into one row but different columns to have one row about each measuring. Combinations of TagID and Instance values can be 21. So I need in the result 21 columns with value in one row (M1....M21). Running on SQL server 2016.

Source table:

ParentID TagID Instance Data
AA 14 2010 117.42
AA 18 3020 0.345
AA 16 2010 1.1234
BB 17 2016 12.1234
BB 09 0 0.0123

Requested table:

ParentID M1 M2 M3 M4 M5 M6
AA 117.42 1.1234 0.345
BB 0.0123 12.1234

Empty columns could be 0 or rather NULL.

EDIT - another column in Source table:

ParentID TagID Instance Data DataText
AA 14 2010 117.42
AA 18 3020 0.345
AA 12 1000 Text1
BB 11 1010 Text2
AA 16 2010 1.1234
BB 17 2016 12.1234
BB 09 0 0.0123

Requested table:

ParentID M1 M2 M3 M4 M5 M6 Text
AA 117.42 1.1234 0.345 Text1
BB 0.0123 12.1234 Text2

CodePudding user response:

you are looking for a PIVOT query like below

select ParentID, [14-2010] [M1], [18-3020] [M2],[16-2010] [M3]
from
(
select 
 ParentID, 
 CAST(TagID as NVARCHAR)   "-"  CAST(Instance AS NVARCHAR) as pivotcol,
 Data
from your table )src
PIVOT( MAX(Data) FOR pivotcol in ([14-2010],[18-3020],[16-2010]))p

I intentionally went upto M3. in your use case feel free to add unique combinations of tagid and instance inside the pivot in sub query part and in the top select part.

  • Related