0

我想从我的表中获取每天记录的计数。例如,我有一个表“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
4

3 回答 3

1

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

创建日历后,使用表将其与表连接,因此表EmployeeLEFT 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
于 2013-04-05T06:19:57.237 回答
0

尝试

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

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

于 2013-04-05T06:13:30.693 回答
0

这可能是查询...

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

在这种情况下,以下内容可能会有所帮助...

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

希望能帮助到你..

于 2013-04-05T06:15:19.583 回答