Mysql 如何在Sql server中对按天分组的时间求和

Mysql 如何在Sql server中对按天分组的时间求和,mysql,sql,sql-server,sql-server-2008,sql-server-2012,Mysql,Sql,Sql Server,Sql Server 2008,Sql Server 2012,我有一张有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 >=

我有一张有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
你能试试这个吗

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)

此版本的SQL server不支持对“master..spt_values”中的数据库和/或服务器名称的引用。您使用的是哪个版本?因此,如果我删除union部分,它工作正常。我认为联盟的一部分是每天都要表现出来,如果没有比赛就0。是吗?是的@既然如此,你在最后一部分中犯了什么错误?