T-SQL中按月和年的销售摘要数据

时间:2013-03-28 15:04:28

标签: sql-server tsql

我所有供应商都按月按销售数据。我希望得到以下结果字段...供应商,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

1 个答案:

答案 0 :(得分: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;