Lucio Gutierrez
Lucio Gutierrez

Reputation: 13

SQL - If two records have same value in two columns, add third column

I have a table with these values:

Col1  | Col2    | Col3 |  
one   | two     |  3   |  
four  | five    |  6   |  
four  | seven   |  8   |  
four  | seven   |  9   |  

I want to make a query that returns a row for every record in which Col1 and Col2 are both different than in every other record, but if they are both the same in two records, the result should be one single row with those values in Col1 and Col2 and their Col3 sum in the third column. The result should be:

Col1  | Col2   | ColNew |  
one   | two    |  3     |  
four  | five   |  6     |  
four  | seven  | 17     |  

Thank you.

Upvotes: 0

Views: 4926

Answers (2)

marc_s
marc_s

Reputation: 754488

Just a really simple, plain GROUP BY and a SUM will do the trick:

SELECT 
    Col1, Col2, ColNew = SUM(Col3)
FROM 
    dbo.YourTable
GROUP BY 
    Col1, Col2

Upvotes: 4

Tricky12
Tricky12

Reputation: 6822

Use GROUP BY on the columns you want to "group by" (1 and 2 in your case). Then use SUM on the column you want to "sum" (3 in your case).

select a.col1, a.col2, sum(a.col3) as colNew
from test as a
group by a.col1, a.col2;

SQLFiddle: http://sqlfiddle.com/#!3/070a3/4

Upvotes: 2

Related Questions