0

我有一个查询,按月提供总销售额。但是,有些月份没有销售。我如何在查询结果中获得该月的 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
4

1 回答 1

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
于 2013-03-15T21:08:05.117 回答