如何获得多行的持续时间总和?

时间:2015-01-08 09:30:33

标签: sql sql-server

我有一张桌子如下图所示,

ID  |  duty |  startDate  |  Enddate


01  | yes  | 2011-10-15  | 2011-12-15

01  | yes  | 2012-01-10  |  2012-05-25

03  | yes  | 2012-02-23  | 2012-03-25

01  | no   | 2012-05-25  |2012-06-06

01  | yes  | 2012-07-10  | 2012-12-03

02  | yes  | 2012-08-21  | 2012-12-10

我需要获得以下结果,

ID | duty | duration (in days)

01 | yes  | xxx

02 | yes  | yyy

03 | yes  | zzz

01 | no   | iii 

1 个答案:

答案 0 :(得分:1)

我会尝试以下内容:

SELECT ID, duty, SUM(DATEDIFF(dd, startDate, endDate)) as duration 
FROM [Table] 
GROUP BY ID, duty

DATEDIFF文档:http://msdn.microsoft.com/en-us/library/ms189794.aspx

不知道GROUP BY是否是您所期待的