简体   繁体   中英

MySQL - Sum values width same ID in same table

I want sum values into my database by the same ID in the same table. Table in database:

| ID | Value_o | Value_t | Value_tt |
|  1 |   40    |    20   |   10     |

query:

SELECT SUM(Value_o) AS Value_o, SUM(Value_t) AS Value_t, SUM(Value_tt) AS Value_TT 
WHERE ID IN(1, 1)

And now the output id:

| Value_o | Value_t | Value_tt |
|   40    |    20   |   10     |

but I want:

| Value_o | Value_t | Value_tt |
|   80    |    40   |   20     |

I want get this output without JOIN.

Thanks!

PS. Sorry for my bad eng :/

Maybe this is what you are looking for:

SELECT 
  SUM(Value_o) AS Value_o, 
  SUM(Value_t) AS Value_t, 
  SUM(Value_tt) AS Value_TT 
FROM
  (
  SELECT ID, Value_o, Value_t, Value_tt FROM Table1 
  UNION ALL 
  SELECT ID, Value_o, Value_t, Value_tt FROM Table1
  ) Table2 
WHERE ID IN(1, 1);

Demo

Try this:

SELECT SUM(Value_o) AS Value_o, SUM(Value_t) AS Value_t, SUM(Value_tt) AS Value_TT 
FROM TABLE
GROUP BY ID
HAVING ID = 1

The MySQL in operator doesn't work this way. Even if you have a value multiple times in the set, it doesn't duplicate the rows of your result.

If you want to have all the rows multiple times, you must use union all and sum over that

SELECT SUM(Value_o) AS Value_o, SUM(Value_t) AS Value_t, SUM(Value_tt) AS Value_TT 
from (select * from mytable union all select * from mytable) t
WHERE ID IN (1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM