有一个日期时间字段,并且想要计算日差。在下一步中,我希望为不同的时间间隔设置不同的列,使用0或1。
基表的结构是名称和日期。
输出应如下所示:
name|date |days|interval 0-31 |interval 31-60|
Tim |2014-12-07 08:04:25.000|1 |1 |0 |
Tom |2014-10-28 08:04:25.000|42 |0 |1 |
提前帮助你!
答案 0 :(得分:0)
如果您想要计算落入指定间隔的记录,那么这样的事情就可以了。只需重复SUM(Case ...行,每个时间间隔修改范围检查。
SELECT
SUM(CASE WHEN DayCount > 0 AND DayCount < 31 THEN 1 ELSE 0 END) AS ZeroTo31
FROM
(SELECT
DATEDIFF(dy, StartDate, EndDate) AS DayCount
FROM YourTable) AS sub
答案 1 :(得分:0)
那么:
SELECT StartDate, DayCount, CASE WHEN DayCount > 0 AND DayCount < 31 THEN 1 ELSE 0 END AS daysZeroTo31,
CASE WHEN DayCount > 31 AND DayCount < 60 THEN 1 ELSE 0 END AS days31to60
FROM (SELECT StartDate, EndDate, DATEDIFF(dy, StartDate, EndDate) AS DayCount
FROM YourTable) AS sub