选择SQL查询中的所有但最大记录

时间:2013-03-06 17:05:16

标签: sql

我一直试图让这个工作,但我没有得到任何地方。我需要的是以下内容:

我需要能够为特定表选择除MAX记录以外的所有记录。我知道如何选择Max记录(通过使用TOP或MAX)但我想显示除此之外的所有记录。有没有办法做到这一点?我已经尝试了下面的代码,但我不断获得MAX记录。

    SELECT 
    rtrim(ltrim(pn.sFirstName + ' ' + pn.uLastName)) as newroom
    FROM tenant t (nolock)
    INNER JOIN room rm (NOLOCK) on t.hmyperson = rm.hmytenant
             and isnull(rm.boccupant,0)=0
             and rm.dtmoveout is null
    INNER JOIN person pn (nolock) on pn.hmy = rm.hmyperson
    WHERE pn.hmy <> 
   (SELECT TOP 1 pn.hmy 
    FROM tenant t (nolock)
    INNER JOIN property p (nolock) on p.hMy = t.hProperty
    INNER JOIN unit u (nolock) on (t.hUnit = u.hMy
    INNER JOIN addr ua (nolock) on u.hmy = ua.hPointer
    INNER JOIN room rm (NOLOCK) on t.hmyperson = rm.hmytenant
             and isnull(rm.boccupant,0)=0
        and rm.dtmoveout is null
        and isnull(rm.dtMoveIn,getdate()) >= getdate()
    INNER JOIN person pn (nolock) on pn.hmy = rm.hmyperson
    WHERE t.code = '011212'
    ORDER BY pn.hmy)
    and t.code = '011212'

在我提取记录之后,我想将MAX记录合并到一个单独的行中。

感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

  

在您的查询中:在第9行 - 将其更改为:

SELECT MAX(pn.hmy)
  

删除第20行。不需要它。

答案 1 :(得分:0)

基本上,你想要这个:

SELECT * FROM tableA WHERE tableA.ID < (SELECT MAX(ID) FROM tableA)

答案 2 :(得分:0)

select
    MaxValue = Max(/* whatever*/),
   -- other required columns
from 
:
:
group by -- as needed
having value <> MaxValue

答案 3 :(得分:0)

感谢您输入..

我离得更近了。我的下一个障碍是试图分开剩余的记录。例如,有多个名称链接到记录。

我希望它是:

NewRoom,NewRoom2

鲍勃史密斯, 乔治威尔逊

我明白了:

NewRoom,NewRoom2

BobSmith

乔治威尔逊

我的代码如下:

   SELECT 
rtrim(ltrim(pn.sFirstName + ' ' + pn.uLastName)) as newroom,
rtrim(ltrim(pn1.sFirstName + ' ' + pn1.uLastName))as newroom2
FROM tenant t (nolock)
INNER JOIN room rm (NOLOCK) on t.hmyperson = rm.hmytenant
         and isnull(rm.boccupant,0)=0
         and rm.dtmoveout is null
INNER JOIN person pn (nolock) on pn.hmy = rm.hmyperson
LEFT OUTER JOIN room rm1 (NOLOCK) on t.hmyperson = rm1.hmytenant
         and isnull(rm1.boccupant,0)=0
         and rm1.dtmoveout is null
LEFT OUTER JOIN person pn1 (nolock) on pn1.hmy = rm1.hmyperson
WHERE (pn.hmy or pn1.hmy) <> 
   (SELECT Max(pn.hmy) 
FROM tenant t (nolock)
INNER JOIN property p (nolock) on p.hMy = t.hProperty
INNER JOIN unit u (nolock) on (t.hUnit = u.hMy
                   and u.sCode not in ('WAIT' ,'COMAREA')
                   and u.scode not like 'NONRES%'
                   and u.exclude = '0' )
INNER JOIN addr ua (nolock) on u.hmy = ua.hPointer
INNER JOIN room rm (NOLOCK) on t.hmyperson = rm.hmytenant
         and isnull(rm.boccupant,0)=0
    and rm.dtmoveout is null
INNER JOIN person pn (nolock) on pn.hmy = rm.hmyperson
WHERE t.scode = 't0029839'

)      和t.scode ='t0029839'

更不用说,我也需要同一行的MAX记录:

MAX_Room,NewRoom,NewRoom2

谢谢大家