根据条件在SQL Server中运行总计

时间:2019-04-22 06:15:45

标签: sql-server

我正在按顺序为特定组创建运行总计。在序列之间发生零值,为此我必须从零记录开始运行总计

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--fix", action="store_true",
                help="increase output verbosity")
args = parser.parse_args()
if args.fix: #this is True for python file_name.py -f
    print("fix is ON")
else: #it will trigger if python file_name.py
    print("fix is OFF")

输出:

select 
    Sno,
    Group,
    Value,
    sum(Value) over(partition by Group order by Sno) Cum_Value 
from 
    Table

1 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

输入:

CREATE TABLE #Data (
    Sno int, 
    [Group] varchar(1),   
    [Value] int
)
INSERT INTO #Data 
   (Sno, [Group], [Value])
VALUES
    (1, 'A', 5), 
    (2, 'A', 10), 
    (3, 'A', 25), 
    (4, 'A', 0),  
    (5, 'A', 10), 
    (6, 'A', 5),  
    (7, 'A', 0),  
    (8, 'A', 20)

声明:

SELECT
    Sno, 
    [Group], 
    [Value],
    Changed,
    SUM([Value]) OVER (PARTITION BY Changed ORDER BY Sno) AS Cum_Value
FROM 
    (
    SELECT 
        Sno, 
        [Group], 
        [Value],
        SUM (CASE 
            WHEN [Value] = 0 THEN 1
            ELSE 0
        END) OVER (PARTITION BY [Group] ORDER BY Sno) AS Changed
    FROM #Data
    ) t

输出:

Sno Group   Value   Cum_Value
1   A       5       5
2   A       10      15
3   A       25      40
4   A       0       0
5   A       10      10
6   A       5       15
7   A       0       0
8   A      20       20