sql

时间:2015-04-22 12:28:12

标签: sql sql-server

我有下表

AssignmentID    UserFrom    UserTo  GroupFrom   GroupTo CreatedOn
201410            NULL      4327    103         103      2014/11/11 09:24.7
201549           NULL      4327     103         103      2014/11/11 09:32.4
201549           NULL      4327     103         103      2014/11/11 09:38.4
 201673         NULL       4328    103          103      2014/12/11 09:56.1
 201673         NULL       4328    103          103      2014/12/11 10:55.1
 201673         NULL       4328    103          103      2014/12/11 10:59.1

我希望在几分钟之内通过userto垂直分组 以下方式。请给我建议以产生以下输出。

 userto   minutes
 4327      8  
 4327      6
 4328     55 
 4328      4

3 个答案:

答案 0 :(得分:1)

在SQL Server 2012+中,您可以使用lag()

select userto, diff
from (select userto,
             datediff(minute, lag(createdon) over (partition by userto order by createdon), createdon) as diff
      from table t
     ) t
where diff is not null;

答案 1 :(得分:1)

如果您使用的是sqlserver 2008,则可以使用CROSS APPLY

请注意,对于同一UserTo中的重复CreatedOn,这将无法正常工作:

SELECT 
  t1.UserTo, 
  DateDiff(minute, 0, t1.CreatedOn - t2.previousCreatedOn) minutes
FROM yourtable t1
CROSS APPLY
(
  SELECT
    MAX(CreatedOn) previousCreatedOn
  FROM yourtable
  WHERE 
    t1.UserTo = UserTo
    AND CreatedOn < t1.CreatedOn
  HAVING 
    MAX(CreatedOn) is not null
) t2

如果您使用的是sqlserver 2012,则可以轻松使用LAG

;WITH CTE AS
(
  SELECT
    userto, 
    datediff(minute, 0, createdon -lag(createdon) over 
      (partition by userto order by createdon)) minutes
  FROM yourtable
)
SELECT userto, minutes
FROM CTE
WHERE minutes is not null

答案 2 :(得分:0)

你可以将表连接到自身,连接条件只允许每一行按时间顺序连接(匹配)同一用户的下一行

Select a.userTo, 
   datediff(minute, a.createdOn, b.CreatedON) minutes
from table a
    join table b 
        on b.userto = a.Userto
           and b.createdon =
                (Select Min(createdOn)
                  From table 
                  Where userTo = a.UserTo
                  and createdOn > a.createdOn)