简体   繁体   English

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

[英]force number of rows to return in date range from SQL query

I'm running a query on our SQL (2012) database which returns a count of records in a given date range, grouped by the date. 我正在SQL(2012)数据库上运行查询,该查询返回给定日期范围内按日期分组的记录数。

For example: 例如:

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

I need to fill in the blanks as the charts I plot get screwed up because there are missing values. 我需要填写空白,因为绘制的图表被搞砸了,因为缺少值。 Is there a way to force the SQL to report back a blank row, or a "0" value when it doesn't come across a result? 有没有一种方法可以强制SQL在未遇到结果时报告空白行或“ 0”值?

My query is 我的查询是

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

Would I need to create a temp table with the records in, then select from that and right join any records from myTable? 我是否需要创建一个包含记录的临时表,然后从中选择并右键连接myTable中的任何记录?

Thanks for any help! 谢谢你的帮助!

If you create a (temporary or permanent) table of the date range, you can then left join to your results to create a result set including blanks 如果您创建日期范围的(临时或永久)表,则可以将其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 

A temp table would do the job but for such a small date range you could go even simpler and use a UNION -ed subquery. 临时表可以完成任务,但是对于这么小的日期范围,您甚至可以变得更简单,并使用UNION -ed子查询。 Eg: 例如:

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

Here's a SQL Fiddle Demo . 这是一个SQL Fiddle演示

If you need a more generic (but also more complex) solution, take a look at this excellent answer (by @RedFilter) to a similar question. 如果您需要一个更通用(但也更复杂)的解决方案,请看一下类似问题的出色答案 (通过@RedFilter)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM