0

我面临一个查询问题。

我的查询是:-

SELECT MONTH(o.OrderDate) as MonthValue, 
       YEAR(o.OrderDate) as YearValue, 
       C.CustomerTypeID, Count(o.Total) as NoOfOrders
FROM Orders o        
RIGHT JOIN Customers C on C.CustomerID = o.CustomerID      

WHERE o.OrderDate >= CONVERT(DATETIME, '1/1/2013 00:00:00 AM')
AND o.OrderDate <= CONVERT(DATETIME, '12/31/2013 23:59:59 PM')
GROUP BY MONTH(o.OrderDate), 
         YEAR(o.OrderDate), 
         C.CustomerTypeID 
ORDER BY MONTH(o.OrderDate),
         YEAR(o.OrderDate),
         C.CustomerTypeID 

它给出的结果如下: -

MonthValue   YearValue   CustomerTypeID   NoOfOrders
1              2013            1             10
1              2013            2             20
1              2013            3             45
2              2013            1             45
2              2013            2             45
3              2013            1             88
3              2013            2             56
3              2013            3             89

至于第 2 个月,客户类型 3 没有结果,因此它不会出现在结果中。

但我想将“0”显示为它的默认结果,如下所示:-

2              2013            3             0

提前致谢。

4

3 回答 3

4

试试这个 :

SELECT  2013 as [Year],
        months.number,
        Amount = SUM(COALESCE(o.Total,0)),
        C.CustomerType
FROM    Customers C
CROSS JOIN
(SELECT number FROM master..spt_values WHERE type='p' and number between 1 and 12) months
LEFT JOIN [Orders] o on C.CustomerId = o.CustomerId and YEAR(o.OrderDate) = 2013 and MONTH(o.OrderDate) = months.number
GROUP BY months.number, C.CustomerType 
ORDER BY months.number, C.CustomerType
于 2013-10-25T12:28:57.790 回答
1

已编辑:您必须在所有月份都加入外部才能获得丢失的条目。因此,为了获得最佳可读性,请先交叉加入所有客户和月份,然后再外部加入订单。

SELECT all_months.MonthValue, 
       all_months.YearValue, 
       C.CustomerTypeID,
       Count(o.Total) as NoOfOrders
FROM 
(
  SELECT distinct MONTH(OrderDate) as MonthValue, YEAR(OrderDate) as YearValue
  FROM orders 
  WHERE YEAR(OrderDate) = 2013
) all_months        
CROSS JOIN Customers C 
LEFT OUTER JOIN Orders o 
  ON o.CustomerID = C.CustomerID 
  AND MONTH(o.OrderDate) = all_months.MonthValue 
  AND YEAR(o.OrderDate) = all_months.YearValue
GROUP BY all_months.MonthValue, 
         all_months.YearValue, 
         C.CustomerTypeID 
ORDER BY all_months.MonthValue,
         all_months.YearValue,
         C.CustomerTypeID ;
于 2013-10-25T12:21:27.820 回答
0

那么你可能会做一个完整的外部连接,它应该给你所有的客户,为丢失的数据重新调整 null。然后,您可以选择 ISNULL(NoOfOrders, 0) 来获取 0 而不是 null。

我不是 100& 确定这会起作用,但你可以试一试。

于 2013-10-25T12:10:23.770 回答