gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:34:27 24 4
gpt4 key购买 nike

我有 billsbill_detailscustomerssuppliers 表我需要进行查询以返回 customerssuppliers

中提交的 area 的总销售额和总返回

我需要所有客户和供应商的相同面积的总和

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

我知道按区域分组是错误的陈述,但我只需要对 s.area 和 c.area 进行分组和求和

最佳答案

使用

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

关于mysql group by 和 sum 结果来自两个表的2个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36845652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com