基于多个条件运行总计

时间:2017-10-30 10:13:55

标签: sql sql-server

我有一个包含列的表格,年份,周,市场,产品销售。我的跑步总数应该是

我尝试过SQL脚本over(order by year, Week, Market, Product ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)。这仅适用于Market&amp ;;的第一套记录集。产品组合。一旦市场和/或产品发生变化,输出仍然会根据最新更新的数据进行计算。

Year    Week    Market  Product  Sale   RunningTotal
2017    1       USA     Shampoo  100    100
2017    2       USA     Shampoo  100    200
2017    3       USA     Shampoo  100    300
2017    1       USA     Soap     100    400
2017    2       USA     Soap     100    500
2017    3       USA     Soap     100    600
2017    1       India   Soap     200    800
2017    2       India   Soap     200    1000
2017    3       India   Soap     200    1200

我正在寻找的结果就是这个

Year    Week    Market  Product  Sale   RunningTotal
2017    1       USA     Shampoo  100    100
2017    2       USA     Shampoo  100    200
2017    3       USA     Shampoo  100    300
2017    1       USA     Soap     100    100
2017    2       USA     Soap     100    200
2017    3       USA     Soap     100    300
2017    1       India   Soap     200    200
2017    2       India   Soap     200    400
2017    3       India   Soap     200    600

2 个答案:

答案 0 :(得分:4)

您需要按市场和产品进行分区:

OVER (
    PARTITION BY Market, Product 
    ORDER BY year, Week 
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)

答案 1 :(得分:0)

我尝试使用sum()Over()函数

;With cte([Year],[Week], Market,Product,Sale)
AS
(
SELECT 2017,1,'USA'  ,  'Shampoo',100 Union all
SELECT 2017,2,'USA'  ,  'Shampoo',100 Union all
SELECT 2017,3,'USA'  ,  'Shampoo',100 Union all
SELECT 2017,1,'USA'  ,  'Soap'   ,100 Union all
SELECT 2017,2,'USA'  ,  'Soap'   ,100 Union all
SELECT 2017,3,'USA'  ,  'Soap'   ,100 Union all
SELECT 2017,1,'India',  'Soap'   ,200 Union all
SELECT 2017,2,'India',  'Soap'   ,200 Union all
SELECT 2017,3,'India',  'Soap'   ,200 
)
SELECT [Year],
        [Week],
        Market,
        Product,
        Sale,
        SUM(Sale)OVER(PARTITION BY Sale,Product ORDER BY RNo ) AS RunningTotal
FROm
(
SELECT *, ROW_NUMBER()OVER(ORDER BY (SELECT 1)) AS RNo from cte
)dt

预期结果

Year    Week    Market  Product  Sale   RunningTotal
2017    1       USA     Shampoo  100    100
2017    2       USA     Shampoo  100    200
2017    3       USA     Shampoo  100    300
2017    1       USA     Soap     100    100
2017    2       USA     Soap     100    200
2017    3       USA     Soap     100    300
2017    1       India   Soap     200    200
2017    2       India   Soap     200    400
2017    3       India   Soap     200    600