0

我有一个包含以下数据的 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 查询中执行此操作?

谢谢

4

1 回答 1

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 小提琴演示

于 2013-05-09T19:25:52.533 回答