[英]MySQL distinct sum without subqueries
I have two main tables bills and billing_items: 我有两个主表bills和billing_items:
bills
_______
id
..
amount
balance
billing_items
______________
id
...
bill_id
I need to get the sum of the bill amount and balance based on certain criteria in the billing_items table (the table references other tables of interest) 我需要根据billing_items表中的某些条件获取账单金额和余额的总和(该表引用了其他感兴趣的表)
when I use the below query I get duplicates: 当我使用下面的查询时,我得到重复:
select sum(b.amount), sum(b.balance)
from bills b left join billing_items bi
on b.id=bi.bill_id;
I can't use subqueries such as the one below because of the ORM I'm using (subqueries not supported): 由于我正在使用ORM,因此无法使用以下子查询(不支持子查询):
select sum(a) from
(select b.amount as a, b.balance
from bills b left join billing_items bi
on b.id=bi.bill_id group by b.id) t;
the criteria on billing_items and its referencing tables is ommited but I need to reference billing_items 省略了billing_items及其引用表的条件,但是我需要引用billing_items
not sure if your ORM allows the use of user variables or not in your SQL, if yes you could try this, basically it's ORDER BY bi.bill_id
and only sum amount when there's a new bill_id
不知道您的ORM是否允许在SQL中使用用户变量,如果可以,您可以尝试一下,基本上是ORDER BY bi.bill_id
,只有在有新的bill_id
select sum(IF (@prevBillId IS NULL OR @prevBillId != bi.bill_id,b.amount,0)) as sumAmount,
sum(IF (@prevBillId IS NULL OR @prevBillId != bi.bill_id,b.balance,0)) as sumBalance,
@prevBillId:=bi.bill_id
from bills b left join billing_items bi
on b.id=bi.bill_id
ORDER BY bi.bill_id;
Hopefully this will work... 希望这会起作用...
So your issue is your left join to billing_items is causing multiple rows per billing item and your sum(b.amount) is being multiplied by the number of rows you have. 因此,您的问题是您对billing_items的左联接导致每个计费项目有多行,并且您的总和(b.amount)乘以您拥有的行数。 So solution...divide your sum by your count. 因此,解决方案...将您的总和除以计数。
select b.id,sum(b.amount) / count(*) as amount, sum(b.balance)
from bills b left join billing_items bi
on b.id=bi.bill_id;
group by b.id
Give that a try...hoping it works out. 试试看...希望它能解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.