并将它们显示为每个月的总数。我使用以下脚本
SELECT datepart(yy,j.CompletedAt) as 'YY',
str(datepart(MM, j.CompletedAt),2) as 'MM',
Datename(MM,j.CompletedAt) as 'Month',
count('MM') as 'PMInMonth'
FROM facts_reactive.dbo.jobs j
WHERE (
(J.Reactive = -1)
AND datepart(yy,j.CompletedAt) = ' 2013'
AND j.jobstatus = 6
)
GROUP BY datepart(yy,j.CompletedAt),
str(datepart(MM, j.CompletedAt),2),
Datename(MM,j.CompletedAt)
ORDER BY datepart(yy,j.CompletedAt) ASC,
str(datepart(MM, j.CompletedAt),2) ASC;
但是,如果当月没有取消工作,则不返还任何工作;而我希望月份和0作为取消工作的数量返回。
这可能吗?
非常感谢提前。
罗布
答案 0 :(得分:1)
;WITH cMONTHS AS
(
SELECT
CAST('20130101' AS date) AS TheMonthStart,
CAST('20130201' AS date) AS TheMonthEnd
UNION ALL
SELECT
DATEADD(mm, 1, TheMonthStart),
DATEADD(mm, 1, TheMonthEnd)
FROM cMONTHS
WHERE TheMonthStart < '20140101'
)
SELECT
datepart(yy,c.TheMonthStart) as 'YY',
str(datepart(MM, c.TheMonthStart),2) as 'MM',
Datename(MM,c.TheMonthStart) as 'Month',
count(j.CompletedAt) as 'PMInMonth'
FROM
cMONTHS c
LEFT JOIN
facts_reactive.dbo.jobs j ON j.CompletedAt >= c.TheMonthStart AND j.CompletedAt < c.TheMonthEnd
AND
J.Reactive = -1
AND
j.jobstatus = 6
GROUP BY
datepart(yy,c.TheMonthStart),
str(datepart(MM, c.TheMonthStart),2),
Datename(MM,c.TheMonthStart)
ORDER BY
datepart(yy,c.TheMonthStart),
str(datepart(MM, c.TheMonthStart),2);