我从这个查询开始:
SELECT TOP 1 Parties.FirstName + ' ' + Parties.MiddleName + ' ' + Parties.LastName AS Plaintiffs
FROM Jackets INNER JOIN
JacketPartyLinks ON Jackets.Id = JacketPartyLinks.Jacket_JacketPartyLink INNER JOIN
Parties ON Parties.Id = JacketPartyLinks.JacketPartyLink_Party
WHERE (Jackets.Id = @JacketID) AND (JacketPartyLinks.Role = 0)
我想要完成的是计算返回的内容,如果是一行,则不执行任何操作。如果它不止一行,请添加"等等#34;。请注意,此查询返回单个列,虽然它应该能够独立运行,但它也需要作为子查询工作。
如何做到这一点?
编辑:添加TOP 1
答案 0 :(得分:4)
使用top
和count..over
,然后将其包装在外部查询中,如下所示:
select
Plantiffs + case when PlantiffCount > 1 then ', et al' else '' end as Plantiffs
from
(
SELECT TOP 1
Parties.FirstName + ' ' + Parties.MiddleName + ' ' + Parties.LastName as Plantiffs,
count(1) over () as PlantiffCount
FROM
Jackets
INNER JOIN JacketPartyLinks ON
Jackets.Id = JacketPartyLinks.Jacket_JacketPartyLink
INNER JOIN Parties ON
Parties.Id = JacketPartyLinks.JacketPartyLink_Party
WHERE
(Jackets.Id = @JacketID) AND (JacketPartyLinks.Role = 0)
order by Parties.LastName asc
) x
over ()
之后的count
部分告诉它计算所有行,而不是group by
任何行。这就是该查询中没有group by
子句的原因。您可以将over
与任何聚合函数一起使用,这非常有效。