mysql group by和sum来自两个表的2个字段的结果

时间:2016-04-25 16:04:57

标签: mysql

我有billsbill_detailscustomerssuppliers个表格 我需要进行查询以返回areacustomers表中提交的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进行分组和求和

1 个答案:

答案 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