如何根据特定条件查找表中的下一个值

时间:2015-12-24 09:38:00

标签: sql sql-server sql-server-2008

我有一张桌子:

UITableView

我想查询此表,结果如下:

ID | Name | Date
 1 | ABC  | 2015-01-01
 2 | XYZ  | 2015-01-02
 3 | ABC  | 2015-01-03
 4 | ABC  | 2015-01-04

一种解决方案是:

ID | Name | Date       | NextDate
 1 | ABC  | 2015-01-01 | 2015-01-03
 2 | XYZ  | 2015-01-02 | null
 3 | ABC  | 2015-01-03 | 2015-01-04
 4 | ABC  | 2015-01-04 | null

但是这很慢,因为我们正在对每一行进行聚合。有没有比这更有效的替代解决方案?

3 个答案:

答案 0 :(得分:3)

由于SQL SERVER 2008不支持LEAD窗口函数,我们必须使用row_numberself join来模拟它。试试这个

;WITH cte
     AS (SELECT t1.*,
                Row_number()
                  OVER(
                    partition BY Name
                    ORDER BY [Date]) AS rn
         FROM   TAB t1)
SELECT a.ID,a.Name,a.Date,b.Date as nextdate
FROM   cte a
       LEFT OUTER JOIN cte b
                    ON a.Name = b.Name
                       AND a.rn + 1 = b.rn ORDER BY a.ID

答案 1 :(得分:1)

写它的另一种方法是。

Select a.*, c.nextDate  from table a 
outer apply (
        Select top 1 b.Date nextDate from table b 
           where b.Id > a.ID and a.Name = b.Name order by b.id 
) c

答案 2 :(得分:0)

    SELECT ID
       ,Name
       ,Date 
       ,(CASE WHEN ID%2 !=0 THEN NextDate ELSE NULL END) AS NextDate
FROM 
(SELECT ID
        ,Name
        ,Date
        ,DATEADD(DAY,1,Date) AS NextDate
FROM YOUR_TABLE) M