0

我有一个看起来像这样的表:

 . |  ID  | SystemID |       StartDateTime       |        EndDateTime        |
1 |  24  |     1    |  2012-11-09 13:59:00.000  |  2012-11-09 14:23:00.000  |
2 |  25  |     2    |  2012-11-09 13:59:00.000  |  2012-11-09 14:23:00.000  |
3 |  26  |     3    |  2012-11-09 14:00:00.000  |  2012-11-09 14:24:00.000  |
4 |  27  |     1    |  2012-11-09 16:20:00.000  |  2012-11-09 17:19:00.000  |
5 |  28  |     2    |  2012-11-09 16:21:00.000  |  2012-11-09 17:37:00.000  |
6 |  29  |     3    |  2012-11-09 17:25:00.000  |  2012-11-09 17:50:00.000  |

对于每个系统 ID,我想选择最接近和在给定时间之前结束的行。例如,如果时间是 17:30,结果将如下所示:

|  ID  | SystemID |       StartDateTime       |        EndDateTime        |
|  27  |     1    |  2012-11-09 16:20:00.000  |  2012-11-09 17:19:00.000  |
|  25  |     2    |  2012-11-09 13:59:00.000  |  2012-11-09 14:23:00.000  |
|  26  |     3    |  2012-11-09 14:00:00.000  |  2012-11-09 14:24:00.000  |

希望这是有道理的!谢谢你的帮助。

4

2 回答 2

0

您可以ROW_NUMBER为此使用:

DECLARE @Date DATETIME
SET @Date = '20121109 17:30:00'

;WITH CTE AS
(
    SELECT  *, 
            ROW_NUMBER() OVER(PARTITION BY SystemID ORDER BY EndDateTime DESC) RN
    FROM YourTable
    WHERE EndDateTime < @Date
)
SELECT ID, SystemID, StartDateTime, EndDateTime
FROM CTE
WHERE RN = 1

这是一个 sqlfiddle供您尝试。

于 2012-11-28T17:39:27.903 回答
0

你可以使用outer apply

select  *
from    (
        select  distinct SystemID
        from    Table1
        ) as ids
outer apply
        (
        select  top 1 *
        from    Table1 t1
        where   t1.SystemID = ids.SystemID
                and t1.EndDateTime < '2012-11-09 17:30'
        order by
                t1.EndDateTime desc
        ) as last

SQL Fiddle 上的实时示例。

于 2012-11-28T17:43:21.130 回答