SQL查询获取每月日常工作的计数

时间:2014-07-06 14:55:23

标签: sql sql-server tsql graph count

我正在构建一个图表,显示已申请实习的申请人的每日计数。使用以下SQL查询,我得到正确的计数, 但我错过了有零申请人的日子。

SELECT YEAR(created) AS [Year],
  MONTH(created) AS [Month],
  DAY(created) AS [Day],
  COUNT(*) AS [Count]
FROM Applicants
GROUP BY
  YEAR(created),
  MONTH(created),
  DAY(created)
Order by [Year],[Month], [DAY] asc

目前的结果是:

Year/Month/Day = Count
2014/01/01 = 1
2014/01/06 = 2

期望的结果将是:

Year/Month/Day = Count
2014/01/01 = 1
2014/01/02 = 0
2014/01/03 = 0
2014/01/04 = 0
2014/01/05 = 0
2014/01/06 = 2
2014/01/07 = 0
2014/01/08 = 0
... etc....

我怎样才能获得整数个月的零数?

2 个答案:

答案 0 :(得分:2)

尝试Bob提到的以下方法;

DECLARE @DateFrom   DATE = '20140101',
        @DateTo     DATE = '20141231'

;WITH DateCTE (xDate) AS
(
    SELECT TOP (DATEDIFF(DAY, @DateFrom, @DateTo) + 1) 
            DATEADD(DD, ROW_NUMBER() OVER (ORDER BY (SELECT NULL))-1, @DateFrom)
    FROM syscolumns T1
    --CROSS                 Uncomment if you need more dates
    --JOIN syscolumns T2
)
SELECT   DT.xDate
        ,[Count]    = ISNULL(DA.[Count], 0)
FROM DateCTE    DT
LEFT
JOIN 
(
    SELECT   [Count]    = COUNT(*)
            ,Created    = CAST(created AS DATE)

    FROM Applicants
    GROUP BY CAST(created AS DATE)
)               DA ON DT.xDate = DA.Created
ORDER BY xDate ASC

答案 1 :(得分:1)

不是相同的表名,但这是在实际数据上测试的

declare @DateStart DateTime
declare @DateEnd DateTime
set @DateStart = CAST((select MIN(addDate) from docSVsys) AS DATE)
set @DateEnd  =  CAST((select MAX(addDate) from docSVsys) AS DATE) 
select @DateStart 
select @DateEnd
 ;WITH Days
as
(
    SELECT @DateStart as [Day]
    UNION ALL
    SELECT DATEADD(DAY, +1, [Day]) as 'Day'
      FROM Days
     where [DAY] <= @DateEnd
)
select [Days].[Day], count([docSVsys].[sID])
  from [Days]
  left join [docSVsys] 
    on cast(docSVsys.addDate AS DATE) = [Days].[Day]
 group by [Days].[Day] 
 order by [Days].[Day]
OPTION (MAXRECURSION 1000);