简体   繁体   English

使用 t-sql 连接列

[英]Concatenate columns with t-sql

I have the following table我有下表

在此处输入图片说明

I need to write a query grouping by Code, DateCod, Room and NumberOfBeds.我需要编写一个按代码、DateCod、Room 和 NumberOfBeds 分组的查询。

For the Name column I need to concatenate names, same action for Booking column and for Num column I need to sum对于 Name 列,我需要连接名称,Booking 列和 Num 列的相同操作我需要求和

The result should be the following结果应该如下

在此处输入图片说明

I'm trying the FOR XML PATH('') approach but I can't find the solution.我正在尝试FOR XML PATH('')方法,但找不到解决方案。 Can someone suggest me a way to do that ?有人可以建议我这样做吗?

Best regards and thanks a lot Fab最好的问候,非常感谢 Fab

You can use STUFF with FOR XML PATH('') to achieve this.您可以使用带有FOR XML PATH('') STUFF来实现此目的。

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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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