【问题标题】:how to sum the time grouped by individual day in Sql-server如何在 Sql-server 中对按天分组的时间求和
【发布时间】:2015-08-20 05:32:48
【问题描述】:

我有一张桌子,上面有 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

【问题讨论】:

    标签: mysql sql sql-server sql-server-2008 sql-server-2012


    【解决方案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)
    

    【讨论】:

    • 此版本的 SQL Server 不支持对“master..spt_values”中的数据库和/或服务器名称的引用。
    • 您使用的是哪个版本?
    • 所以如果我删除联合部分,它工作正常。我认为联合部分是每天显示,如果没有玩游戏,则显示 0。是吗?
    • 是的.. @Asbat 就是为了这个
    • 您在最后一个联合部分遇到的错误是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    相关资源
    最近更新 更多