如何查询从该月的第一天到最后一天的记录数

时间:2013-04-05 06:10:23

标签: sql sql-server

我想从我的桌子上得到每天记录的数量。 例如,我有一个表“Employee”,其中包含以下字段ID,EmpNo,DateHired。 我有以下记录

ID  EmpNo       DateHired
1   000001      3/2/2013 12:00:00 AM
2   000002      3/14/2013 12:00:00 AM
3   000003      3/14/2013 12:00:00 AM
4   000004      3/21/2013 12:00:00 AM
5   000005      4/2/2013 12:00:00 AM
6   000006      4/3/2013 12:00:00 AM
7   000007      4/3/2013 12:00:00 AM
8   000008      4/3/2013 12:00:00 AM
9   000009      4/3/2013 12:00:00 AM
10  000010      4/4/2013 12:00:00 AM
11  000011      4/5/2013 12:00:00 AM
12  000012      5/1/2013 12:00:00 AM

当月是四月, 我怎样才能得到这个值:

Count   Day
0   4/1/2013 12:00:00 AM
1   4/2/2013 12:00:00 AM
4   4/3/2013 12:00:00 AM
1   4/4/2013 12:00:00 AM
1   4/5/2013 12:00:00 AM
0   4/6/2013 12:00:00 AM
0   4/7/2013 12:00:00 AM
0   4/8/2013 12:00:00 AM
Up to
0   4/30/2013 12:00:00 AM

3 个答案:

答案 0 :(得分:1)

您需要为整月创建一个日历,以获取该月的整个日期。借助Common Table Expression,你可以得到你想要的东西。

创建日历后,使用Employee将其与表格LEFT JOIN结合使用,以便日期在表Employee上没有匹配项仍会包含在结果中。

WITH April_Calendar
AS
(
  SELECT CAST('20130401' as datetime) AS [date]
  UNION ALL
  SELECT DATEADD(dd, 1, [date])
  FROM   April_Calendar
  WHERE  DATEADD(dd, 1, [date]) <= '20130430'
)
SELECT a.date, COUNT(b.DateHired) totalCount
FROM   April_Calendar a
       LEFT JOIN Employee b
          ON a.date = b.DateHired
GROUP  BY a.date
ORDER  BY a.date

答案 1 :(得分:0)

尝试

SELECT   COUNT(*) as 'Count', DateHired as 'Day'
FROM     Employee
WHERE    DateHired BEWTEEN %date1 AND %date2
GROUP BY DateHired

未经测试,应该可以工作。

答案 2 :(得分:0)

这可能是查询......

SELECT COUNT(ID) as Count, DateHired FROM Employee GROUP BY DateHired

以下情况可能有所帮助......

http://www.sqlite.org/lang_datefunc.html

希望有所帮助......