1

我正在我们的 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 中的任何记录?

谢谢你的帮助!

4

2 回答 2

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 
于 2013-10-16T14:38:14.237 回答
0

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

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 演示

如果您需要更通用(但也更复杂)的解决方案,请查看这个针对类似问题的出色答案(@RedFilter 提供)。

于 2013-10-16T14:36:32.260 回答