mysql 按聚合分组作为列

mysql group by aggregation as column

我有一个 table,其中包含两个相关字段 namevalue。 我想进行查询,为我提供每个名称的所有负值和所有正值的总和。

我得到的最好的是以下代码:

SELECT `name`,sign(`value`),sum(`value`)
FROM `testing` 
WHERE `value` != 0 
GROUP BY `name`,sign(`value`)

它给了我这些结果:

name | sign(`value`) | sum(`value`)
-----------------------------------
A    |      -1       |    -9
A    |       1       |    21
B    |      -1       |   -35
B    |       1       |     8
C    |      -1       |   -16
C    |       1       |    21

哪些是我想要但不是我想要的结果。

我能不能让它看起来像这样?

name |  -1  |   1
-------------------
A    |  -9  |  21
B    | -35  |   8
C    | -16  |  21

这是我的第一个问题,所以我希望我没有以完全羞辱的方式写它。

提前致谢。

在这种情况下,case 语句会派上用场。

select name,
sum(case when value > 0 then value else 0 end) as positive_sum,
sum(case when value < 0 then value else 0 end) as negative_sum
from testing
group by name;