我在sql查询中遇到问题。我附加了Schema。
我想要的是。我想生成一个将产生如下结果的查询。
=======================================================================================
showroom_id | total_salary | total_expense | total_sold | balance
=======================================================================================
| 1 | 2000 | 8000 | 30000 | 20000
=======================================================================================
| 2 | 1000 | 4000 | 25000 | 20000
=======================================================================================
| 3 | 3000 | 7000 | 30000 | 20000
====================================================================================
我想按展厅ID进行分组,并将费用金额,员工工资,项目价格相加并在每一行中显示。然后,另一个列余额将显示total_sold -( total_expanse + total_salary)
。我该如何进行查询?
答案 0 :(得分:2)
select
s.id as showroom_id,
sal.amount as total_salary,
exp.amount as total_expense
-- not sure where to get total_sold amount?
from showroom as s
left outer join (
select sum(t.amount) as salary, t.showroom_id
from staff_salary as t
group by t.showroom_id
) as sal on sal.showroom_id = s.id
left outer join (
select sum(t.amount) as salary, t.showroom_id
from expense as t
group by t.showroom_id
) as exp on exp.showroom_id = s.id