2月销售额高于1月的前10家分支机构

时间:2019-05-13 05:59:45

标签: sql-server

我需要显示一家商店的前10家分支机构的结果,这些分支机构2月份的月销售额都比1月份大。

我的专栏看起来像这样-

BranchID
SaleDate
SaleAmount

我尝试按branchid和salesdate月份进行分区,但是我不确定如何将分组与分区合并。

select branchid, 
       datepart(month, saledate) as month, 
       sum(saleamount) over (partition by datepart(month, saledate), branchid  order by saledate) as 'Monthly Sales' 
from sales

1 个答案:

答案 0 :(得分:0)

如果您要查找从1月到2月销售量最高的前10名,那么您可以在下面这一种方法。

SELECT TOP(10) --Get top 10
        [BranchID],
        ISNULL(SUM(
            CASE WHEN MONTH([SaleDate]) = 2
            THEN [SaleAmount]
            ELSE 0 END
        ),0) as [SaleAmountFeb], --Sum all Feb sales
        ISNULL(SUM(
            CASE WHEN MONTH([SaleDate]) = 1
            THEN [SaleAmount]
            ELSE 0 END
        ),0) as [SaleAmountJan], --Sum all Jan sales

        ISNULL(SUM(
            CASE WHEN MONTH([SaleDate]) = 2
            THEN [SaleAmount]
            ELSE 0 END
        ),0) - 
        ISNULL(SUM(
            CASE WHEN MONTH([SaleDate]) = 1
            THEN [SaleAmount]
            ELSE 0 END
        ),0) as [Increase in Sales] --Increase in sales Jan to Feb

    FROM sales
    GROUP BY
        [BranchID]
    ORDER BY
        4 DESC --Order by Increase in sales Jan to Feb (Largest to smallest)