获取每月创建的订单数

时间:2019-09-29 15:14:50

标签: sql sql-server

我正在尝试列出最近12个月(不包括当月)的订单总数。

这是我的查询

Select
Year(CreatedOn)*100+Month(CreatedOn) YearMonth,
Count(*) OrderCount
From Orders
Where DateDiff(MM,CreatedOn,GetUTCDate()) Between 1 And 12
Group By Year(CreatedOn), Month(CreatedOn)
Order By YearMonth

按预期,我正确地得到了结果。但是,当特定月份没有订单时,该月份将从结果中完全排除。我想显示该月为0。请参阅示例结果:

201809  70
201810  8
201811  53
201812  67
201901  15
201902  13
201903  10
201905  12
201908  9

请参阅缺少的月份201904、201906和201907。总共应该有12行。

该查询应在使用For XML Path的子查询中可执行,这样我才能获得最近12个月内以逗号分隔的订单列表。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您需要以某种方式生成想要的行。一种方法使用递归CTE:

nordland$N <- 1
myplot <- ggplot(nordland, aes(x = Date, y = N)) +
          geom_col() +
          labs(x = "Date", y = "Number of firms",
               title = "Number of new firms per month")
           theme(plot.title = element_text(hjust = 0.5))

答案 1 :(得分:1)

检查此-

WITH R(N) AS
(
    SELECT 1
    UNION ALL
    SELECT N+1 
    FROM R
    WHERE N < 12
)
SELECT REPLACE(LEFT(CAST (DATEADD(MONTH,DATEDIFF(MONTH,0,(DATEADD(MONTH,-N,GetUTCDate()))),0) AS DATE),7),'-','') AS [YearMonth],ISNULL(o.OrderCount,0) as OrderCount 
FROM R A
LEFT JOIN 
(       
    Select
    Year(CreatedOn)*100+Month(CreatedOn) YearMonth,
    Count(*) OrderCount
    From Orders
    Where DateDiff(MM,CreatedOn,GetUTCDate()) Between 1 And 12
    Group By Year(CreatedOn), Month(CreatedOn)
) O ON O.YearMonth=REPLACE(LEFT(CAST (DATEADD(MONTH,DATEDIFF(MONTH,0,(DATEADD(MONTH,-N,GetUTCDate()))),0) AS DATE),7),'-','')
Order By REPLACE(LEFT(CAST (DATEADD(MONTH,DATEDIFF(MONTH,0,(DATEADD(MONTH,-N,GetUTCDate()))),0) AS DATE),7),'-','');