Skip to content
Advertisement

Running total over duplicate column values and no other columns

I want to do running total but there is no unique column or id column to be used in over clause.

CREATE TABLE piv2([name] varchar(5), [no] int);

INSERT INTO piv2
    ([name], [no])
VALUES
    ('a', 1),
    ('a', 2),
    ('a', 3),
    ('a', 4),
    ('b', 1),
    ('b', 2),
    ('b', 3);

there are only 2 columns, name which has duplicate values and the no on which I want to do running total in SQL Server 2017 .

expected result:

a 1
a 3
a 6
a 10
b 11
b 13
b 16

Any help?

Advertisement

Answer

The following query would generate the output you expect, at least for the exact sample data you did show us:

SELECT
    name,
    SUM(no) OVER (ORDER BY name, no) AS no_sum
FROM piv2;

If the order you intend to use for the rolling sum is something other than the order given by the name and no columns, then you should reveal that logic along with sample data.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement