从同一个表中的行中选择值和下一个最高值

时间:2014-11-30 07:24:41

标签: sql-server-2008 tsql

我有一张这样的表

LowerPoints MessageTemplate
0           zero
10          ten
100         hundred

我想从中进行选择,因此我有一个lowerPoints列表,然后是LowerPoints

的NEXT最低值

e.g。

select
    low.LowerPoints As LowerPoints
    , high.LowerPoints as UpperPoints
    , low.MessageTemplate as MessageTemplate
from MessageTemplate low
    , MessageTemplate high
where high.LowerPoints = (select top 1 LowerPoints from MessageTemplate where LowerPoints > low.LowerPoints order by LowerPoints)

返回

LowerPoints UpperPoints MessageTemplate
0           10          zero
10          100         ten

但是我看不出如何获得第三个值并给它一个" null" UpperPoints的值。即最后一行是

100                     hundred

2 个答案:

答案 0 :(得分:2)

您使用过时的语法,用逗号分隔表格将被视为INNER JOIN。 你可以把它写成:

select
    low.LowerPoints As LowerPoints
    , high.LowerPoints as UpperPoints
    , low.MessageTemplate as MessageTemplate
from MessageTemplate low
LEFT JOIN MessageTemplate high
ON high.LowerPoints = (select top 1 LowerPoints from MessageTemplate where LowerPoints > low.LowerPoints order by LowerPoints)

您也可以使用简单的子选择

Declare @a Table (LowerPoints int, MessageTemplate varchar(30))
insert into @a Values(0,'zero'),(10,'ten'),(100,'hundred')

Select a.LowerPoints
     ,(Select top 1 LowerPoints from @a b 
       where b.LowerPoints>a.LowerPoints
       order by b.LowerPoints) as UpperPoints
     ,a.MessageTemplate
from @a a
Order by LowerPoints

或CTE生成一个定义的行号(rn),对于条件b.rn = a.rn + 1

,其自身为LEFT JOIN
;With CTE as
(
Select LowerPoints,MessageTemplate
       ,ROW_NUMBER() OVER (ORDER by LowerPoints) as rn
from @a a
)
Select c1.LowerPoints
      ,c2.LowerPoints as UpperPoints
      ,c1.MessageTemplate 
from CTE c1
LEFT JOIN CTE c2 on c2.rn=c1.rn +1 
Order by c1.LowerPoints

答案 1 :(得分:0)

--create temp table   
 IF object_id('tempdb..#test') IS NOT NULL
        DROP TABLE #test
    CREATE TABLE #test  (LowerPoint INT,MessageTemplate VARCHAR(10))
    INSERT INTO #test VALUES (0 ,'Zero'), (10,'ten'), (100,'hundred');
------------------------------------------------------------------------

    WITH cte
    AS (SELECT *,row_number() OVER (ORDER BY LowerPoint) AS RN
        FROM #test)

    SELECT a.LowerPoint
        ,b.LowerPoint AS UpperPoints
        ,a.MessageTemplate
    FROM cte a
    LEFT JOIN cte b
        ON (a.rn + 1) = b.rn