两列成一个单个单元格的SQL查询

时间:2015-01-29 11:26:43

标签: sql sql-server subquery correlated-subquery

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名儿童

现在它只给予成年人

2 个答案:

答案 0 :(得分:1)

使用条件聚合:

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()更容易控制结果字符串的格式,而不是将一堆表达式连接在一起。

答案 1 :(得分:0)

for sql server 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