我有4个具有相同列的表(id
& banka_id
& miktar
)。
2个表格收入(drink_earn
,eat_earn
)和
2桌消费(drink_spending
,eat_spending
)
|id|banka_id|miktar|
---|--------|------|
|1 |2 |20 |
|2 |1 |20 |
|3 |1 |30 |
我的问题。
如何计算行中的所有内容?
drink_earn
:表SUM(miktar)= 50 $
eat_earn
:表SUM(miktar)= 50 $
drink_spending
:表SUM(miktar)= 15 $
eat_spending
:表SUM(miktar)= 5 $
收入:drink_earn
+ eat_earn
= 100 $
支出:drink_spending
+ eat_spending
20 $
总计:收入 - 消费= 80美元
最后是GROUP BY banka_id
你能写代码样本吗?问候。
答案 0 :(得分:0)
使用UNION ALL将所有表合并为一个:
select banka_id, sum(earn) - sum(spend) as total
from (
select banka_id, miktar as earn, 0 as spend
from drink_earn
union all
select banka_id, miktar as earn, 0 as spend
from eat_earn
union all
select banka_id, 0 as earn, miktar as spend
from drink_spending
union all
select banka_id, 0 as earn, miktar as spend
from eat_spending
) t
group by banka_id
但如果你只有一个表中的所有数据以及一个额外的类型列,那就更好了。