【问题标题】:SQL: How to build sum per day with emptySQL:如何用空来建立每天的总和
【发布时间】:2026-02-16 13:20:05
【问题描述】:

我想从每小时的价值中得出总和。 看截图:

为此,我使用了“datepart”。 现在,我想要时间戳格式的日期部分中的这些值。 此外,我想填满一天中的其他时间,所以我想每天有 24 行。

你能帮帮我吗?

【问题讨论】:

    标签: sql sum timestamp summary datepart


    【解决方案1】:

    首先,创建一个Numbers Table

    然后这样做:

    select N1.Number, 
           sum(case when P2.Typ = 'outbound' then 1 else 0 end) as Outbound,
           sum(case when P2.Typ = 'inbound' then 1 else 0 end) as Inbound
    
    from Numbers N1
    left join #pstntable P2
      on N1.Number = DatePart(hh, P2.Date)
      and P2.Date between @_StartTime and @_EndTime
    
    where N1.Number <= 24
    
    group by N1.Number
    

    【讨论】:

    • 感谢您的回答!如何制作包含以下字段的数字表:时间 2016-09-22 01:00:00 2016-09-22 02:00:00 2016-09-22 03:00:00 2016-09-22 04: 00:00 2016-09-22 05:00:00 2016-09-22 06:00:00 2016-09-22 07:00:00 2016-09-22 08:00:00 2016-09-22 09: 00:00 等等..
    • @Patrik 你不会想要的。这里的想法是,您有一个可以拉回的数字表,可以应用于您喜欢的任何一天。如果您希望完整日期显示在列中,请在选择中执行此操作
    最近更新 更多