Home > Mobile >  SQL add values of different rows with same ID
SQL add values of different rows with same ID

Time:06-11

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?

CodePudding user response:

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

CodePudding user response:

you use aggregation function SUM

SELECT code, SUM(duration) FROM table1 GROUP BY code
  •  Tags:  
  • sql
  • Related