[英]mysql total and difference for multiple rows
I'm new to mysql. 我是mysql新手。 I'm trying to write a query to calculate the total and difference for multiple rows, and then put them in specific columns. 我正在尝试编写一个查询来计算多个行的总数和差异,然后将它们放在特定的列中。
Eg. 例如。 I want to sum all Entity'A' of Type'1' then subtract from the result, the sum of Entity'A' of type'0'. 我想对所有类型为“ 1”的实体“ A”求和,然后从结果中减去类型为“ 0”的实体“ A”的总和。 While simultaneously populating a table to show where this difference is positive or negative. 同时填充表格以显示此差异为正还是负。
Sample table: 样表:
Entity Type Value
A 1 200
B 1 500
C 0 350
B 0 150
C 1 100
A 1 50
A 1 350
Expected Output: 预期产量:
Entity Diff-Positive Diff-Negative
A 600
B 350
C 250
Note that Entity'A' for example may not have an entry for Type'0' 注意,例如,实体“ A”可能没有类型“ 0”的条目
This is basically aggregation. 这基本上是聚合。 You need a conditional to split the values into separate columns. 您需要一个条件来将值拆分为单独的列。 One way uses greatest()
: 一种方法使用greatest()
:
select entity,
greatest(sum(case when type = 1 then value else - value end), 0) as diff_positive,
greatest(sum(case when type = 0 then value else - value end), 0) as diff_positive
from t
group by entity;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.