Home > OS >  SQL How to SUM rows in second column if first column contain
SQL How to SUM rows in second column if first column contain

Time:08-31

View of a table

ID kWh
1 3
1 10
1 8
1 11
2 12
2 4
2 7
2 8
3 3
3 4
3 5

I want to recive

ID kWh
1 32
2 31
3 12

The table itself is more complex and larger. But the point is this. How can this be done? And I can't know in advance the ID numbers of the first column.

CodePudding user response:

SELECT T.ID,SUM(T.KWH)SUM_KWH
FROM YOUR_TABLE T
GROUP BY T.ID

Do you need this one?

CodePudding user response:

Let's assume your database name is 'testdb' and table name is 'table1'.

    SELECT * FROM testdb.table1;
    SELECT id, SUM(kwh) AS "kwh2"
    FROM stack.table1
    WHERE id = 1

keep running the query will all (ids). you will get output.

By following this query you will get desired output.

Hope this helps.

  •  Tags:  
  • sql
  • Related