我有一个查询,按月给出总销售额。但是,有几个月没有销售。如何在查询结果中获得该月份的0值?
SELECT
p.Part,
SUM(s.Sales) AS Sales,
MONTH(s.SalesDate) AS Month_Sold
FROM
Parts p
LEFT OUTER JOIN Sales s ON p.Part = s.Part
GROUP BY
p.Part,
MONTH(s.SalesDate)
ORDER BY
p.Part,
Month_Sold
答案 0 :(得分:2)
执行SUM(ISNULL(s.Sales, 0))
以便聚合不会消除您的NULL值。虽然,由于您的销售数据也依赖于您的月份,因此您需要查看月份,以便即使您的销售数据中没有这些月份,也可以查看所有月份。
所以,像这样:
;WITH months AS
(
SELECT 1 AS mo
UNION ALL
SELECT mo +1
FROM months
WHERE mo < 12
)
SELECT p.Part, SUM(s.Sales) AS Sales, mo AS Month_Sold
FROM Parts p
CROSS APPLY months
LEFT OUTER JOIN Sales s
ON p.Part = s.Part
AND months.mo = MONTH(s.SalesDate)
GROUP BY p.Part, months.mo ORDER BY p.Part, Month_Sold