我有bills
,bill_details
,customers
和suppliers
个表格
我需要进行查询以返回area
和customers
表中提交的suppliers
的总销售额和总回报
我需要所有客户和供应商的相同领域的总和
select c.area,s.area,
sum( IF(b.bill_type = 'sales', bd.quantity*(bd.price-bd.discount), 0) ) as totalSales,
sum( IF(b.bill_type = 'salesReturns', bd.quantity*(bd.price-bd.discount), 0) ) as totalReturns,
sum( IF(b.bill_type = 'sales', bd.quantity, 0) ) as sales,
sum( IF(b.bill_type = 'salesReturns', bd.quantity, 0) ) as returns
from adsl_bill b
left join bill_details bd on bd.bill_num = b.bill_num && bd.bill_type = b.bill_type
left join customers c on b.customer = c.id && b.customer_type = 1
left join suppliers s on b.customer = s.id && b.customer_type = 2
group by area
我知道group by area
是错误的陈述,但我只需要对s.area和c.area进行分组和求和
答案 0 :(得分:1)
使用
select ifnull(c.area, s.area) as area,
sum( IF(b.bill_type = 'sales', bd.quantity*(bd.price-bd.discount), 0) ) as totalSales,
sum( IF(b.bill_type = 'salesReturns', bd.quantity*(bd.price-bd.discount), 0) ) as totalReturns,
sum( IF(b.bill_type = 'sales', bd.quantity, 0) ) as sales,
sum( IF(b.bill_type = 'salesReturns', bd.quantity, 0) ) as returns
from adsl_bill b
left join bill_details bd on bd.bill_num = b.bill_num && bd.bill_type = b.bill_type
left join customers c on b.customer = c.id && b.customer_type = 1
left join suppliers s on b.customer = s.id && b.customer_type = 2
group by area