Home > Back-end >  SQL sum all rows by id
SQL sum all rows by id

Time:07-18

I am trying to learn SQL queries and have this scenario where I have this table:

Table1

       ID | Name | Hour
       ----------------
        1 | Mark | 2
        2 | ken  | 1.5
        3 | jake | 3
        1 | Mark | 1.8
        2 | ken  | 1

Expected result

       ID | Name | Hour
       ----------------
        1 | Mark | 3.8
        2 | ken  | 2.5
        3 | jake | 3
   

I have tried to use the sum() function but I get an error.

My query:

Select ID, Name, Sum(Hour) 
From Table1 
Where ID = ID

Response:

  1. Kindly use Group by clause whenever the Aggregate functions (min(),max(),sum(),count(),...etc.,) and columns are used together.

  2. Non aggregated columns present in SELECT columns should be used in GROUP BY clause.

CodePudding user response:

For using aggregate function you need to use Group By like this:

 Select ID, Name , Sum(Hour) AS Hour From Table1
 Group By ID, Name
 Order By ID
  •  Tags:  
  • sql
  • Related