1

我有一个查询,它将显示所有选定的记录,除了 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'

谢谢你的帮助!

4

2 回答 2

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。外部查询汇总数据,使用条件选择第二个到第六个值。

于 2013-03-22T13:59:53.267 回答
0

您需要一个变量来保存该信息,例如

declare @result;
set @result = '';

select @result = @result + ',' + rtrim(ltrim(pn.sFirstName + ' ' + pn.uLastName))  
from ..... 

select substring(@result, 0, len(@result));
于 2013-03-22T13:47:21.770 回答