我想要没有值存在的记录计数

时间:2018-03-08 11:29:48

标签: sql sql-server

我附上了这些结果,我想要的只是那些日子和时间。小时和没有计数的天数记录。

感谢下面是我使用的查询

SELECT dateadd(hour, datediff(hour, 0, date_sent_to_adobe), 0) as TimeStampHour, Count(*) 'Total Count this Hour'
FROM [Publication_Data_Management].[AdobeExtract].[Membership_Detail]
GROUP BY dateadd(hour, datediff(hour, 0, date_sent_to_adobe), 0)
ORDER BY dateadd(hour, datediff(hour, 0, date_sent_to_adobe), 0) desc

是因为查询的编写方式只会在表格中显示日期,如何重写查询以显示没有记录数的每小时的天数。见附图。 enter image description here

1 个答案:

答案 0 :(得分:0)

您可以生成所有行,然后使用left joingroup by来引入行。这是一种方法:

SELECT DATEADD(hour, h.hr, d.dte) as TimeStampHour,
       Count(*) as total_count
FROM (SELECT DISTINCT CAST(date_sent_to_adobe as DATE) as dte
      FROM Publication_Data_Management.AdobeExtract.Membership_Detail
     ) d CROSS JOIN
     (VALUE (0), (1), (2), . . ., (23) ) as h(hr) LEFT JOIN
     Publication_Data_Management.AdobeExtract.Membership_Detail md
     ON md.date_sent_to_adobe >= DATEADD(hour, h.hr, d.dte) AND
        md.date_sent_to_adobe < DATEADD(hour, h.hr + 1, d.dte)
GROUP BY DATEADD(hour, h.hr, d.dte)
ORDER BY DATEADD(hour, h.hr, d.dte) DESC;