SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

后端 未结 5 2108
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 11:54

I have a table with two fields - datetime and int. I want to do a group by on the datetime only on the date ignoring the hour and minute.

5条回答
  •  既然无缘
    2021-02-01 12:26

    -- I like this as the data type and the format remains consistent with a date time data type

    ;with cte as(
        select 
            cast(utcdate as date) UtcDay, DATEPART(hour, utcdate) UtcHour, count(*) as Counts
        from dbo.mytable cd 
        where utcdate between '2014-01-14' and '2014-01-15'
        group by
            cast(utcdate as date), DATEPART(hour, utcdate)
    )
    select dateadd(hour, utchour, cast(utcday as datetime)) as UTCDateHour, Counts
    from cte
    

提交回复
热议问题