我有这张表register
id quantity type
1 | 10 | in
2 | 5 | in
1 | 3 | out
1 | 2 | out
2 | 5 | out
3 | 2 | in
3 | 1 | out
我想要每个股票的余额[类型的总和='在' - 类型的总和=' out' ]
期望的输出将是
1 | 5
2 | 0
3 | 1
我还有另一张表item
id | name
1 | A
2 | B
3 | C
是否可以使用项目名称而不是ID来查看输出? 所以最终结果就像
A | 5
B | 0
C | 1
答案 0 :(得分:3)
基本思想是case
内的条件聚合 - sum()
。您还需要join
才能获得name
:
select i.name,
sum(case when r.type = 'in' then quantity
when r.type = 'out' then - quantity
else 0
end) as balance
from register r join
item i
on r.id = i.id
group by i.name;
答案 1 :(得分:1)
根据上述问题中提到的描述,作为解决方案,请尝试执行以下SQL查询
SELECT i.name,
@in_total:= (select sum(quantity) from register where type = 'in'
and id = r.id group by id),
@out_total:= (select sum(quantity) from register where type = 'out'
and id = r.id group by id),
@balance:= (@in_total - @out_total) as balance
FROM `register`
as r join item i on r.id = i.id group by r.id
CROSS JOIN (SELECT @in_total := 0,
@out_total := 0,
@balance := 0) AS user_init_vars