Skip to content
Advertisement

SQL add values of different rows with same ID

Query:

SELECT code, duration 
FROM table1

results in

code duration
234 3
345 2
345 3
456 4
567 5
567 6
567 1

I would like to add the durations of the same code and display results as here

code duration
234 3
345 5
456 4
567 12

but I don’t know where to start with this query?

Advertisement

Answer

You can use GROUP BY together with SUM. When using GROUP BY, aggregate functions (such as SUM) will return the output of the function as if every value in the specified column for the entire group was passed to it. In this case you can tell it to run on duration.

SELECT code, SUM(duration) as TotalDuration FROM table1 GROUP BY code
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement