获取两个日期列之间的差异最小的行

时间:2014-12-02 13:56:52

标签: sql sql-server

我有下表(这只是一个示例):

id  User    dateAssigned          dateComment
---|-------|---------------------|---------------------|
1  | Usr1  | 2014-12-02 12:35:00 | 2014-12-03 08:13:00 |
2  | Usr1  | 2014-12-02 12:35:00 | 2014-12-02 13:06:00 |
3  | Usr2  | 2014-12-02 07:47:00 | 2014-12-02 07:47:00 |
4  | Usr2  | 2014-12-02 07:47:00 | 2014-11-25 08:07:00 |

如何在SQL Server 2008中编写查询,为每个用户选择行之间的区别 dateAssigneddateComment最低限度?在我的示例中,查询应返回第2行和第3行。

谢谢。

3 个答案:

答案 0 :(得分:7)

您可以使用CTE(公用表格式)和ROW_NUMBER function

WITH CTE AS
(
    SELECT id,  [User], dateAssigned, dateComment,
           rn = ROW_NUMBER() OVER ( 
                     PARTITION BY [User] 
                     ORDER BY ABS(DATEDIFF(minute, dateAssigned, dateComment)) ASC)
    FROM dbo.Users u
)
SELECT id, [User], dateAssigned, dateComment
FROM CTE
WHERE RN = 1

答案 1 :(得分:1)

使用此:

SELECT * 
FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY Username 
                               ORDER BY ABS(DATEDIFF(second, dateComment, dateAssigned)) ASC) AS datesOrder
  FROM @T ) t
WHERE t.datesOrder = 1

对应于最小差异的记录,行号等于1。因此,外部select语句中的where子句检索所需的记录。

修改

我添加了应用于日期差异的ABS函数,因为dateAssigned也可以在dateComment之前。

答案 2 :(得分:0)

只是为了好玩,当然row_number + partition by更好更快

select * from #t
outer apply (
  select top 1 id from #t t1
  where t1.usr = #t.usr
  order by abs(datediff(second, dateAssigned, dateComment))
) o
where #t.id = o.id