强制在SQL查询的日期范围内返回的行数

时间:2013-10-16 13:32:00

标签: sql sql-server datetime

我在SQL(2012)数据库上运行查询,该数据库返回给定日期范围内的记录数,按日期分组。

例如:

Date    Count
12/08   12
14/08   19
19/08   11

我需要填写空白作为我绘制的图表因为缺少值而被搞砸了。有没有办法强制SQL报告一个空行,或者当它没有遇到结果时为“0”值?

我的查询是

SELECT TheDate, count(recordID) 
FROM myTable 
WHERE (TheDate between '12-AUG-2013 00:00:00' and '20-AUG-2013 23:59:59')
GROUP BY TheDate

我是否需要创建一个包含记录的临时表,然后从中选择并右键加入来自myTable的任何记录?

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

如果您创建日期范围的(临时或永久)表格,则可以left join到结果中创建包含空白的结果集

 SELECT dates.TheDate, count(recordID) 
 FROM 
 ( select 
      convert(date,dateadd(d,number,'2013-08-12')) as theDate 
   from master..spt_values 
   where type='p' and number < 9
 ) dates
 left join yourtable on dates.thedate = convert(date,yourtable.thedate)
 GROUP BY dates.TheDate 

答案 1 :(得分:0)

临时表可以完成这项工作,但是对于这么小的日期范围,您可以更简单地使用UNION - ed子查询。 E.g:

SELECT dates.TheDate, ISNULL(counts.Records, 0)
FROM
(SELECT TheDate, count(recordID) AS Records
 FROM myTable 
 WHERE (TheDate between '12-AUG-2013 00:00:00' and '20-AUG-2013 23:59:59')
 GROUP BY TheDate
) counts
RIGHT JOIN
(SELECT CAST('12-AUG-2013' AS DATETIME) AS TheDate
 UNION ALL SELECT CAST('13-AUG-2013' AS DATETIME) AS TheDate
 UNION ALL SELECT CAST('14-AUG-2013' AS DATETIME) AS TheDate
 UNION ALL SELECT CAST('15-AUG-2013' AS DATETIME) AS TheDate
 UNION ALL SELECT CAST('16-AUG-2013' AS DATETIME) AS TheDate
 UNION ALL SELECT CAST('17-AUG-2013' AS DATETIME) AS TheDate
 UNION ALL SELECT CAST('18-AUG-2013' AS DATETIME) AS TheDate
 UNION ALL SELECT CAST('19-AUG-2013' AS DATETIME) AS TheDate
 UNION ALL SELECT CAST('20-AUG-2013' AS DATETIME) AS TheDate
) dates
ON counts.TheDate = dates.TheDate

这是SQL Fiddle Demo

如果您需要更通用(但也更复杂)的解决方案,请查看this excellent answer(@RedFilter)查询类似问题。