我想计算每个ID的天数,但天数重叠。
ID STARTDATE ENDDATE
1 19/12/2012 29/01/2013
1 30/05/2013 14/07/2013
1 15/02/2013 12/03/2013
1 13/03/2013 18/03/2013
1 19/03/2013 26/03/2013
1 27/01/2013 07/04/2013
1 08/04/2013 09/04/2013
2 08/04/2013 14/07/2013
2 30/05/2013 12/07/2013
3 08/04/2013 10/04/2013
3 23/05/2013 30/06/2013
答案 0 :(得分:0)
SELECT SUM(DATEDIFF( d,STARTDATE,ENDDATE)) AS [Days],ID
FROM TABLE
GROUP BY ID
或者从MIN / MAX DATE范围获取天数:
SELECT D.ID, SUM(DATEDIFF( d,D.STARTDATE,D.ENDDATE)) AS [Days]
FROM (
SELECT ID, MIN(STARTDATE) AS [STARTDATE], MAX(ENDDATE) AS [ENDATE]
FROM TABLE
GROUP BY ID , MIN(STARTDATE), MAX(ENDDATE)
) AS D
ORDER BY D.ID