我写了一个查询
WITH sample AS (
SELECT CAST('2010-01-01' AS DATETIME) AS d
UNION ALL
SELECT DATEADD(dd, 1, i.vrp_notificationdate) as deneme
FROM Incident i
WHERE DATEADD(dd, 1, i.vrp_notificationdate) <= CAST('2011-11-01' AS DATETIME))
SELECT count(DATENAME(mm,l.vrp_notificationdate) +' '+DATENAME(yy,l.vrp_notificationdate)) as Toplam,DATENAME(mm,l.vrp_notificationdate) +' '+DATENAME(yy,l.vrp_notificationdate)
FROM Incident as l
group by
DATENAME(mm,l.vrp_notificationdate) +' '+DATENAME(yy,l.vrp_notificationdate)
查询显示
10 November 2011 101 October 2011 4 September 2011
但我想表明这一点。
0 january 2010 0 february 2010 - - - 10 November 2011 101 October 2011 4 september 2011 0 december 2011 0 february 2011
我尝试了case语句,但查询显示相同的结果 如何解决我使用的问题
最好的问候。
答案 0 :(得分:2)
您正在尝试显示不存在的数据。这个解决方案的想法是
DECLARE @StartDate DATE = '01-01-2010'
;WITH Dates(d) AS (
SELECT @StartDate
UNION ALL
SELECT DATEADD(mm, 1, d) AS Date
FROM Dates
WHERE d < '12-01-2012'
)
,WITH sample AS (
SELECT CAST('2010-01-01' AS DATETIME) AS d
UNION ALL
SELECT DATEADD(dd, 1, i.vrp_notificationdate) as deneme
FROM Incident i
WHERE DATEADD(dd, 1, i.vrp_notificationdate) <= CAST('2011-11-01' AS DATETIME)
)
SELECT SUM(Toplam) AS Toplam
, DateFormat
FROM (
SELECT COUNT(DATENAME(mm,l.vrp_notificationdate) + ' ' + DATENAME(yy,l.vrp_notificationdate)) AS Toplam
, DATENAME(mm,l.vrp_notificationdate) + ' ' + DATENAME(yy,l.vrp_notificationdate) AS DateFormat
, CONVERT(VARCHAR(6), l.vrp_notificationdate, 112) as orderDate
FROM Incident as l
GROUP BY
DATENAME(mm,l.vrp_notificationdate) + ' ' + DATENAME(yy,l.vrp_notificationdate)
, CONVERT(VARCHAR(6), l.vrp_notificationdate, 112)
UNION ALL
SELECT 0 AS Toplam
, DATENAME(mm, d) + ' ' + DATENAME(yy, d)
, CONVERT(VARCHAR(6), d.d, 112) as orderDate
FROM Dates d
) g
GROUP BY
DateFormat
ORDER BY
g.orderDate
答案 1 :(得分:0)
嗯,如果日期没有出现,则表示该日期没有任何值。因此,无法将该日期显示在结果中。
要通过这个,最简单的解决方案是:
select countValues + ' ' + dateValues from newTable
如果您有任何疑问,请询问:)
答案 2 :(得分:0)
为什么不使用样本时会提供“WITH sample AS”?
我使用这个递归查询来构建结果表的所有日期。
WITH sample (d) AS (
SELECT CAST('2010-01-01' AS DATETIME)
UNION ALL
SELECT DATEADD(mm, 1, d) FROM sample WHERE DATEADD(mm, 1, d) <= CAST('2011-11-01' AS DATETIME)
)
select * from sample
然后,您可以将此表与您的事件表外连接,以获取每个月的事件计数。
如果你想看到很多个月甚至几天,你可能会因为过多的递归而得到一个MSG 530。在这种情况下,您需要在“select * from sample”之后添加OPTION(MAXRECURSION)。