我有一张包含id,play,starttime和endtime的表。我想找到每天的总播放时间。我认为查询将类似于以下,但我相信它是不对的。如果我在没有比赛的情况下获得0,但是如果我很难,我也不会介意,这也会非常方便。
Select
id,
play,
date,
CASE
WHEN datediff(day, starttime, endtime) = 0 then sum(totaltime)
END as TimePerDay
from cte where starttime >= '2015-05-30 17:11:34.000'
group by id, playtime, starttime, endtime
我正在寻找
id | play | Date | totaltime
1 | hockey | 05/06/2015 | 0
2 | hockey | 04/06/2015 | 0
3 | hockey | 03/06/2015 | 230
4 | hockey | 02/06/2015 | 10
5 | hockey | 01/06/2015 | 120
答案 0 :(得分:1)
你能试试吗
Select play, cast(starttime as date) as date,
SUM(datediff(MINUTE, endtime, starttime)) as TimePerDay
from cte
where starttime >= '2015-05-30 17:11:34.000'
group by play, cast(starttime as date)
union
SELECT 'hockey', DATEADD(DAY,number+1,(select min(starttime) from cte)) as date, 0 as TimePerDay
FROM master..spt_values
WHERE type = 'P'
AND DATEADD(DAY,number+1,(select min(starttime) from cte)) < (select max(starttime) from cte)
and CAST(DATEADD(DAY,number+1,(select min(starttime) from cte)) as date) not in (select cast(starttime as date) from cte)
快递版:
DECLARE @startDate date = (select min(starttime) from cte)
DECLARE @endDate date = (select max(starttime) from cte)
;WITH dates(Date) AS
(
SELECT @startdate as Date
UNION ALL
SELECT DATEADD(d,1,[Date])
FROM dates
WHERE DATE < @enddate
)
Select play, cast(starttime as date) as date,
SUM(datediff(MINUTE, endtime, starttime)) as TimePerDay
from cte
where starttime >= '2015-05-30 17:11:34.000'
group by play, cast(starttime as date)
union
SELECT 'hockey' as play, Date, 0 as TimePerDay
FROM dates
where Date not in (select cast(starttime as date) from cte)