SQL - 在按多列分组后查找日期的差异

时间:2016-08-04 15:58:48

标签: sql sql-server group-by date-difference

我在表格中有以下数据

enter image description here

我想了解以下详情

  • 对于给定的游戏和ID,找出2个州的日期(以天为单位)之间的差异
  • 对于给定的游戏和ID,找到两个州之间的平均日期

例如 对于游戏100和ID 1000,日期之间的差异应为4天,avarage应为2。

我们可以使用单个查询来实现吗?`

Game    ID  State   Date
100 1000    1111    5/6/2016
101 1001    1111    5/7/2016
102 1002    1111    5/8/2016
103 1003    1111    5/9/2016
100 1000    2222    5/10/2016
101 1001    2222    5/11/2016
102 1002    2222    5/12/2016
103 1003    2222    5/13/2016

感谢。

3 个答案:

答案 0 :(得分:0)

DECLARE @tbl TABLE (
    Game INT
    ,ID INT
    ,STATE INT
    ,DATE DATE
    );

INSERT INTO @tbl
VALUES (100,1000,1111,'5/6/2016'),(101,1001,1111,'5/7/2016'),
(102,1002,1111,'5/8/2016'),(103,1003,1111,'5/9/2016'),
(100,1000,2222,'5/10/2016')
,(101,1001,2222,'5/11/2016'),(102,1002,2222,'5/12/2016'),
(103,1003,2222,'5/13/2016')

--select * from @tbl

SELECT state1.game
,state1.ID
,state1.STATE
,state2.state
,state1.DATE as '1111Date'
,state2.Date as '2222Date'
,datediff(dd, state1.DATE, state2.DATE) AS 'DateDiff'
,datediff(dd, state1.DATE, state2.DATE) / 2 as 'Avg days'
FROM (
    SELECT game,id,STATE,DATE
    FROM @tbl) state1
INNER JOIN (
    SELECT game,id,STATE,DATE
    FROM @tbl) state2 ON state1.Game = state2.Game
         AND state1.ID = state2.ID
 WHERE datediff(dd, state1.DATE, state2.DATE) > 0

答案 1 :(得分:0)

如果你有sql server 2012,你可以使用滞后函数

DECLARE @tbl TABLE (
    Game INT
    ,ID INT
    ,STATE INT
    ,DATE DATE
    );

INSERT INTO @tbl
VALUES (100,1000,1111,'5/6/2016'),(101,1001,1111,'5/7/2016'),
(102,1002,1111,'5/8/2016'),(103,1003,1111,'5/9/2016'),
(100,1000,2222,'5/10/2016')
,(101,1001,2222,'5/11/2016'),(102,1002,2222,'5/12/2016'),
(103,1003,2222,'5/13/2016')

select * from (
select *
,lag(state,1,null) over (partition by Game,ID order by [date] desc) state2
,lag(Date,1,null) over (partition by Game,ID order by [date] desc) date2
,datediff("dd",[date],lag(Date,1,null) over (partition by Game,ID order by [date] desc)) [days]
,datediff("dd",[date],lag(Date,1,null) over (partition by Game,ID order by [date] desc))/2 ave
 from @tbl
 ) x
 where date2 is not null 

答案 2 :(得分:-1)

SELECT g1.Game, g1.ID
    , DateDiff(dd,g1.[Date], g2.[Date]) as Diff
    , DateDiff(dd,g1.[Date], g2.[Date])/(SELECT COUNT(DISTINCT [State]) as States FROM Games) as DiffAvg 
FROM Games as g1
INNER JOIN Games as g2
ON g1.Game = g2.Game and g1.ID = g2.ID
ORDER BY g1.Game, g1.ID