TSQL返回第一条记录

时间:2013-05-09 19:16:46

标签: sql sql-server-2008 tsql

我有一个SQL Server 2008表,其中包含以下数据(小样本)

id                                          Date    Value
20448D6F-4099-408D-85FE-11EC6690CDB8    2010-06-01  1
20448D6F-4099-408D-85FE-11EC6690CDB8    2010-06-02  2
20448D6F-4099-408D-85FE-11EC6690CDB8    2010-06-03  3
20448D6F-4099-408D-85FE-11EC6690CDB8    2010-06-04  4
20448D6F-4099-408D-85FE-11EC6690CDB8    2010-06-05  NULL
EF595DE6-FF57-4625-8254-287F49843445    2010-06-02  2
EF595DE6-FF57-4625-8254-287F49843445    2010-06-03  3
EF595DE6-FF57-4625-8254-287F49843445    2010-06-04  4
EF595DE6-FF57-4625-8254-287F49843445    2010-06-05  NULL
C6F459EF-1493-4864-81C2-E5B55283EF0C    2010-06-04  45
C6F459EF-1493-4864-81C2-E5B55283EF0C    2010-06-05  NULL

我正在运行查询

select * 
from [test].[dbo].[testtable]
where id in 
         (
            select id 
            from [test].[dbo].[testtable] 
             where Date='2010-06-05' and Value is null
          )
  and Date = DATEADD(D, -4, '2010-06-05')

返回

id                                          Date            Value
20448D6F-4099-408D-85FE-11EC6690CDB8    2010-06-01          1

但是当2010-06-01的记录不存在时,我想返回下一个最小日期

所以我从样本中看到的结果将是

id                                          Date            Value
20448D6F-4099-408D-85FE-11EC6690CDB8    2010-06-01          1
EF595DE6-FF57-4625-8254-287F49843445    2010-06-02          2
C6F459EF-1493-4864-81C2-E5B55283EF0C    2010-06-04          45

我有数百万条记录如何在T-SQL查询中执行此操作?

由于

1 个答案:

答案 0 :(得分:0)

您可以在子查询中使用MIN聚合:

SELECT t.Id, t.Date, t.Value
FROM [test].[dbo].[testtable] t
    JOIN (
        SELECT Min(Date) MinDate, Id
        FROM [test].[dbo].[testtable] 
        WHERE Date >= '6/1/2010'
        GROUP BY Id
    ) t2 ON t.Id = t2.Id AND t.Date = t2.MinDate
WHERE t.Id IN (
    SELECT id 
    FROM [test].[dbo].[testtable] 
    WHERE Date='2010-06-05' and Value is null
    )

SQL Fiddle Demo