SQL Server Combine multiple rows in to one with the same ID [duplicate]

wfauudbj  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(97)

This question already has answers here:

Efficiently convert rows to columns in sql server (5 answers)
Closed 16 days ago.

I currently have the table structure below where I have a custom ID called SubNo which ties all of the records from that insert together but ideally in an SQL query i need all of the values to output as one row for each SubNo

SubNoTypeFIDFVal
2173SOSYourNameJ Bloggs
2173SOSYourDate2023-10-30
2173SOSYourTime07:30
2174SOSYourNameN.E Body
2174SOSYourDate2023-10-31
2174SOSYourTime09:00

This is what I am trying to achieve is this output

SubNoTypeYourNameYourDateYourTime
2173SOSJ Bloggs2023-10-3007:30
2174SOSN.E Body2023-10-3109:00

I currently run the SQL query

SELECT *
FROM [dbo].[Core] 
WHERE Type = 'SOS' 
  AND FID IN ('YourName','YourDate','YourTime')
ORDER BY SubNo DESC
    OFFSET 0 ROWS FETCH FIRST 2 ROWS ONLY

which returns the first table

I have tried to use JOIN and STRING_AGG without success.

q3qa4bjr

q3qa4bjr1#

If you know the columns in advance you can use the conditional aggregation using MAX() :

select SubNo, Type, max(case when FID = 'YourName' then FVal end) as YourName,
                    max(case when FID = 'YourDate' then FVal end) as YourDate,
                    max(case when FID = 'YourTime' then FVal end) as YourTime
from mytable
where Type = 'SOS'
group by  SubNo, Type

Demo here

相关问题