两列合并为一个单元格 SQL 查询

Two columns into One single cell SQL query

Select COALESCE(
(Select Convert(nvarchar(20),Count(ID))+' '+'Adult(s) - ' From TourPerson Where BookingID = 1 And [Type] = 1),
(Select Convert(nvarchar(20),Count(ID))+' '+'Child(s)' From TourPerson Where BookingID = 1 And [Type] = 2)  
) as TotalPassengers

我想采用下面提到的格式

1 名成人 - 0 名儿童

现在只给大人

使用条件聚合:

select sum(case when [Type] = 1 then 1 else 0 end) as NumAdults,
       sum(case when [Type] = 2 then 1 else 0 end) as NumChildren
from TourPerson
where BookingId = 1;

可以在应用层进行格式化。如果你真的想要它作为一个字符串,我建议使用 replace():

select replace(replace('<a> Adult - <c> Children',
                       '<a>', sum(case when [Type] = 1 then 1 else 0 end)
                      ),
               '<c>', sum(case when [Type] = 2 then 1 else 0 end)
              )
from TourPerson
where BookingId = 1;

我发现使用 replace() 比将一堆表达式连接在一起更容易控制结果字符串的格式。

对于 sql 服务器 2012

Select concat(
(Select Convert(nvarchar(20),Count(ID))+' '+'Adult(s) - ' 
From TourPerson 
Where BookingID = 1 And [Type] = 1),
(Select Convert(nvarchar(20),Count(ID))+' '+'Child(s)' 
From TourPerson 
Where BookingID = 1 And [Type] = 2)  
) as TotalPassengers