SQL显示自定义记录

时间:2018-02-07 12:12:06

标签: sql sql-server

我有两个日期,例如2018年2月201日和2018年2月2日

我希望以小时为单位显示一些新用户,例如

            Date                  Total
    ---------------------------------------------
    01-Feb-2018 12:00:00 AM |      25
    01-Feb-2018 01:00:00 AM |      50
   ..................
   .................
   ............
   02-Feb-2018 11:00:00 PM  |      45

我想在SQL中使用这样的结果。 如果你提出一个想法,请欣赏。

2 个答案:

答案 0 :(得分:0)

一种相对简单的方法:

select cast(date as date) as dte, datepart(hour, date) as hh, count(*)
from t
group by cast(date as date), datepart(hour, date)
order by dte, hh;

这并不是完全你想要的东西,因为它有两个独立的列。您实际上可以将它们组合为:

select dateadd(hour, datepart(hour, date), cast(date as date)) as yyyymmddhh, count(*)
from t
group by cast(date as date), datepart(hour, date)
order by yyyymmddhh;

答案 1 :(得分:0)

您可以获得所需的输出,如followng。

DECLARE @MyTable TABLE  ([Date] DateTime, [Name] VARCHAR(100) )
INSERT INTO @MyTable
    SELECT * FROM 
    ( VALUES 
         ('2018-02-07 15:20:27.487','A')
         ,('2018-02-07 15:22:27.487','B')
         ,('2018-02-07 14:22:27.487','C')
        )T ([Date]  , [Name]    )

    SELECT DateWithHour, COUNT(*) AS Total
    FROM
    (
      SELECT convert(char(14),[Date],121)+'00:00' AS DateWithHour,[Name]
      FROM @MyTable
    ) T
    GROUP BY DateWithHour
    ORDER BY DateWithHour

以下是输出

DateWithHour           Total
-------------------   ----------
2018-02-07 14:00:00     1
2018-02-07 15:00:00     2