MySQL - Sum值在同一个表中宽度相同的ID

时间:2013-03-17 21:39:17

标签: php mysql

我想通过同一个表中的相同ID将sum值输入到我的数据库中。 数据库中的表:

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

查询:

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

现在输出id:

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

但我想:

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

我希望在没有JOIN的情况下获得此输出。

谢谢!

PS。抱歉我的坏人:/

3 个答案:

答案 0 :(得分:1)

也许这就是你要找的东西:

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

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

MySQL in运算符不能以这种方式工作。即使您在集合中有多次值,也不会复制结果的行。

如果您希望多次拥有所有行,则必须使用union all并对其进行总结

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)