我有一个查询将显示所有选定的记录,除了MAX记录(每个查询最多可以有5条记录)。但是,它会在不同的行上显示它。如何在一行中显示结果?
当前数据:
John Smith
Jack Smith
Gerald Smith
一行中的所需数据(或在单独的字段中但不是多行):
约翰史密斯;杰克史密斯;杰拉尔德史密斯SQL语句:
SELECT distinct /*all existing records */
rtrim(ltrim(pn.sFirstName + ' ' + pn.uLastName)) as record1,
'' as record2,
'' as record3,
'' as record4,
'' as record5
FROM tenant t (nolock)
INNER JOIN person pn (nolock) on pn.hmy = t.person
WHERE pn.hmy <>
(SELECT MAX(pn.hmy)
FROM tenant t (nolock)
INNER JOIN person pn (nolock) on pn.hmy = t.person
WHERE t.scode = '111111'
)and t.scode = '111111'
感谢您的帮助!
答案 0 :(得分:2)
看起来您正在使用SQL Server。如果您使用的是2005或更高版本,则可以使用row_number()
:
SELECT (case when seqnum = 2 then rtrim(ltrim(max(pn.sFirstName+ ' ' + pn.uLastName))) as record1,
(case when seqnum = 3 then rtrim(ltrim(max(pn.sFirstName+ ' ' + pn.uLastName))) as record2,
(case when seqnum = 4 then rtrim(ltrim(max(pn.sFirstName+ ' ' + pn.uLastName))) as record3,
(case when seqnum = 5 then rtrim(ltrim(max(pn.sFirstName+ ' ' + pn.uLastName))) as record4,
(case when seqnum = 6 then rtrim(ltrim(max(pn.sFirstName+ ' ' + pn.uLastName))) as record5
FROM (select pn.*,
ROW_NUMBER() over (partition by t.scode order by pn.hmy desc) as seqnum
from tenant t (nolock) INNER JOIN
person pn (nolock)
on pn.hmy = t.person
where t.scode = '111111'
) pn
内部查询根据pn.hmy
分配序号,最大值为1.外部查询汇总数据,使用条件选择第二到第六个值。
答案 1 :(得分:0)
您需要一个变量来保存该信息,例如
declare @result;
set @result = '';
select @result = @result + ',' + rtrim(ltrim(pn.sFirstName + ' ' + pn.uLastName))
from .....
select substring(@result, 0, len(@result));