简体   繁体   中英

Concatenate columns with t-sql

I have the following table

在此处输入图片说明

I need to write a query grouping by Code, DateCod, Room and NumberOfBeds.

For the Name column I need to concatenate names, same action for Booking column and for Num column I need to sum

The result should be the following

在此处输入图片说明

I'm trying the FOR XML PATH('') approach but I can't find the solution. Can someone suggest me a way to do that ?

Best regards and thanks a lot Fab

You can use STUFF with FOR XML PATH('') to achieve this.

Query

select 
  t.[Code], 
  t.[DateCod],
  t.[Room],
  t.[NrBeds],
  stuff((select ',' + t.[Name]
    from [your_table_name] t1
    where t1.[Code] = t.[Code]
    for xml path, type).value('.[1]', 'nvarchar(max)'), 1, 1, '') as [Name],
  stuff((select ',' + t.[Booking]
    from [your_table_name] t1
    where t1.[Code] = t.[Code]
    for xml path, type).value('.[1]', 'nvarchar(max)'), 1, 1, '') as [Booking],
  sum(t.Num) as [Num]
from [your_table_name] t
group by t.[Code], t.[DateCod], t.[Room], t.[NrBeds];

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