SQL Server:计数/分组依据

时间:2014-03-19 15:01:29

标签: sql sql-server group-by

我有一个orders表,我需要按月/年生成这些组的报告,显示该月的总订单和实际收到的数量。

这给了我按月/年的订单总数:

SELECT YEAR(o.OrderDate) As 'Year'
    , MONTH(o.OrderDate) As 'Month'
    , COUNT(ID) As 'OrderCount'
FROM Orders o 
GROUP BY YEAR(o.OrderDate), MONTH (o.OrderDate)
ORDER BY YEAR(o.OrderDate) DESC, MONTH (o.OrderDate) DESC

这给了我按月/年收到的订单总数:

SELECT YEAR(o.OrderDate) As 'Year'
    , MONTH(o.OrderDate) As 'Month'
    , COUNT(o.ID) As 'OrderReceivedCount'
FROM Orders o
INNER JOIN OrderStatus s ON s.ID = o.CurrentStatus 
WHERE s.StatusPriority > 4 AND s.IsCancelled = 0
GROUP BY YEAR(o.OrderDate), MONTH (o.OrderDate)
ORDER BY YEAR(o.OrderDate) DESC, MONTH (o.OrderDate) DESC

但是如何将其合并为一个查询?我无法通过'来解决这个问题。会工作吗?

1 个答案:

答案 0 :(得分:2)

我想你想要这样的东西:

SELECT YEAR(o.OrderDate) As [Year]
    , MONTH(o.OrderDate) As [Month]
    , COUNT(*) As OrderCount
    , SUM(CASE
            WHEN s.StatusPriority > 4 AND
                 s.IsCancelled = 0 THEN 1
            ELSE 0 END) as OrderReceivedCount
FROM Orders o
INNER JOIN OrderStatus s ON s.ID = o.CurrentStatus 
GROUP BY YEAR(o.OrderDate), MONTH (o.OrderDate)
ORDER BY YEAR(o.OrderDate) DESC, MONTH (o.OrderDate) DESC

即将所有订单加入其状态,无论它们是什么,然后对这些订单进行有条件计数(通过SUM/CASE)以确定哪些订单已被接收。