SQL查询以按类别获取每个月的产品销售额

时间:2016-01-11 18:29:19

标签: sql sql-server sql-server-2008

您好我正在寻找一个查询来获取每个月的每个产品类别的销售额

我有两个类别

Catid CatName
1     Dispenser
2     Refill

我使用以下查询来获取所有产品类别的总销售额

SELECT YEAR(OrderDate) as [Sales Year],
MONTH(OrderDate) as [Sales Month],
SUM(TotalAmount) AS [Total Sales]
FROM Orders
GROUP BY YEAR(OrderDate), MONTH(OrderDate)
ORDER BY YEAR(OrderDate), MONTH(OrderDate)

输出以上查询

Sales Year  Sales Month        Total Sales  
2015            6              1000.00  
2015            7              2000.00  

如何获得每个产品类别的总销售额

out put应该是这样的

   Sales Year   Sales Month        Dispenser-sales      Refill-sales         
    2015            6              500.00                 500.00      
    2015            7              500.00                 1500.00 

我的架构

Schema

2 个答案:

答案 0 :(得分:1)

您必须onItemClickListener涉及的其他表(基于显示的架构)并使用条件聚合,以按类别ID进行拆分。

join

答案 1 :(得分:1)

您可能希望使用动态sql和PIVOT执行此操作,这样您就不必知道catid catname组合。

另外,您可能希望对Orderdetails Quantity * UnitPrice求和,以获得单个类别金额,而不是订单总金额。

DECLARE @SQL VARCHAR(MAX),
        @Columns VARCHAR(MAX)
SELECT @Columns = COALESCE(@Columns + ',', '') + QUOTENAME(CatName)
FROM Category

SET @Sql = '
    SELECT * FROM
    (
        SELECT  YEAR(o.OrderDate) [Sales Year],
                MONTH(o.OrderDate) [Sales Month],
                c.CatName,
                od.Quantity * od.UnitPrice AS [CatAmount]
        FROM    Orders o
                JOIN OrderDetails od ON o.Order_ID = od.Orderid
                JOIN Store s ON od.Proid = s.Pro_ID
                JOIN Category c ON s.CatID = c.Catid
    ) T
    PIVOT
    (
        SUM([CatAmount])
        FOR CatName IN (' + @Columns + ')
    ) p
    ORDER BY [Sales Year], [Sales Month]'

EXEC(@Sql)

如果您只想要特定的类别,您可以在不使用动态SQL的情况下将名称硬编码到数据透视表中。

SELECT * FROM
(
    SELECT  YEAR(o.OrderDate) [Sales Year],
            MONTH(o.OrderDate) [Sales Month],
            c.CatName,
            od.Quantity * od.UnitPrice AS [CatAmount]
    FROM    Orders o
            JOIN OrderDetails od ON o.Order_ID = od.Orderid
            JOIN Store s ON od.Proid = s.Pro_ID
            JOIN Category c ON s.CatID = c.Catid
) T
PIVOT
(
    SUM([CatAmount])
    FOR CatName IN ([Dispenser-sales],[Refill-sales])
) p
ORDER BY [Sales Year], [Sales Month]