2

I have the following data:

a  b
1  23
1  14
1  3
2  45
2  16

and what I would like is to sum column b where column a is the same and have this displayed in a third column, like so:

a  b  c
1  23 40
1  14 40
1  3  40
2  45 61
2  16 61

Thanks.

1
  • Please tag your question with the DBMS you are using.
    – mustaccio
    Commented May 29, 2018 at 15:02

1 Answer 1

4

You didn't specify your RDBMS, but here is a solution using SQL Server

Declare @T table (a int, b int)
INSERT INTO @T
    (a, b)
VALUES
    (1, 23),
    (1, 14),
    (1, 3),
    (2, 45),
    (2, 16)
;

select 
    a,b,sum(b) over (partition by a)  as c
from @T

| a | b  | c  |
|---|----|----|
| 1 | 23 | 40 |
| 1 | 14 | 40 |
| 1 | 3  | 40 |
| 2 | 45 | 61 |
| 2 | 16 | 61 |

If your RDBMS doesn't support Window Functions, you could use a common table expression to do the sum/group and then join that cte to the original table. The results are the same.

;WITH _cte
AS (
    SELECT a
        ,sum(b) AS c
    FROM @T
    GROUP BY a
    )
SELECT t.a
    ,t.b
    ,c.c
FROM @T t
JOIN _cte c ON c.a = t.a
3
  • Yes, SQL server. The first solution worked. Thanks very much!
    – Jimothous
    Commented May 29, 2018 at 15:20
  • Sorry, new to this, as you can probably tell!
    – Jimothous
    Commented May 29, 2018 at 15:23
  • @Jimothous - take the tour, visit the help centre. Read this and this carefully - for future reference, for this type of question, it would be great if you could provide a fiddle. These sites are a great resource and you will get all the more out of them if you follow the guidelines - p.s. welcome to the forum!
    – Vérace
    Commented May 29, 2018 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.