0

我有我所有供应商的逐月销售数据。我正在寻找以下结果字段...供应商、2012 年销售额、2013 年销售额、2012 年平均每月销售额、2013 年每月预计销售额。最后一个字段是我遇到最多问题的字段。我需要平均过去 5 个月的完整销售数据,然后将其乘以 12。这是我正在处理的查询...

SELECT
    a.Vendor,
    a.Vendor_Name,
    SUM(a.Sales2012) AS Sales_2012,
    SUM(a.Sales2013) AS Sales_2013
FROM
(SELECT
    Vendor,
    Vendor_Name,
    CASE
        WHEN Month_Sold IN ('201201','201202','201203','201204','201205','201206','201207','201208','201209','201210','201211','201212') THEN SUM(Sales_Dlr) END AS 'Sales2012',
    CASE
        WHEN Month_Sold IN ('201301','201302','201303','201304','201305','201306','201307','201308','201309','201310','201311','201312') THEN SUM(Sales_Dlr) END AS 'Sales2013'
FROM
    dbo.SalesSummary
GROUP BY
    Vendor,
    Vendor_Name,
    Month_Sold
)a
GROUP BY
    a.Vendor,
    a.Vendor_Name
ORDER BY
    a.Vendor_Name
4

1 回答 1

1

假设 SalesSummary.Vendor 是一个 ID,您可以尝试添加最近 5 个月的子查询,然后在外部查询中乘以 12:

DECLARE @Today DATE = GETDATE();

SELECT
    a.Vendor,
    a.Vendor_Name,
    SUM(a.Sales2012) AS Sales_2012,
    SUM(a.Sales2013) AS Sales_2013,
    b.Sales_Dlr_Avg * 12 AS [Monthly Projected Sales]
FROM
(SELECT
    Vendor,
    Vendor_Name,
    CASE
        WHEN Month_Sold IN ('201201','201202','201203','201204','201205','201206','201207','201208','201209','201210','201211','201212') THEN SUM(Sales_Dlr) END AS 'Sales2012',
    CASE
        WHEN Month_Sold IN ('201301','201302','201303','201304','201305','201306','201307','201308','201309','201310','201311','201312') THEN SUM(Sales_Dlr) END AS 'Sales2013'
FROM
    dbo.SalesSummary
GROUP BY
    Vendor,
    Vendor_Name,
    Month_Sold
)a
JOIN (
    SELECT Vendor, Sales_Dlr_Avg = AVG(Sales_Dlr)
    FROM dbo.SalesSummary
    WHERE DATEDIFF(MONTH, CAST(Month_Sold AS VARCHAR(6)) + '01', @Today) BETWEEN 1 AND 5
    GROUP BY Vendor
) b ON b.Vendor = a.Vendor
GROUP BY
    a.Vendor,
    a.Vendor_Name,
    b.Sales_Dlr_Avg
ORDER BY
    a.Vendor_Name;
于 2013-03-28T15:25:34.830 回答