这是一个查询,它将获得您问题中显示的结果集。但是,业务规则可能无法完全实施,因为仅从输出中很难破译。此外,这可能最好用过程语言完成,因为它需要跨行进行一些计算。
它利用左右外连接和联合从两个表中获取所有行。
select cashbilling_id,
ifnull(cashbillingreturn_id,min_cashbillingreturn_id) cashbillingreturn_id,
article_id,
total,
diff,
ifnull(cashbillingreturn_date,min_cashbillingreturn_date) cashbillingreturn_date
from(
select cashbilling_id,
ifnull(a_article_id,b_article_id) article_id,
cashbillingbillarticle_total,
cashbillingreturnarticle_total,
ifnull(cashbillingreturnarticle_total,cashbillingbillarticle_total) total,
ifnull(cashbillingreturnarticle_total,0) - ifnull(cashbillingbillarticle_total,0) diff,
cashbillingreturn_id,
cashbillingreturn_date,
case when @group_id = cashbilling_id then @min_id
when @group_id != cashbilling_id then @min_id := cashbillingreturn_id
when @group_id := cashbilling_id then @min_id := cashbillingreturn_id
end min_cashbillingreturn_id,
case when @date_group_id = cashbilling_id then @min_date
when @date_group_id != cashbilling_id then @min_date := cashbillingreturn_date
when @date_group_id := cashbilling_id then @min_date := cashbillingreturn_date
end min_cashbillingreturn_date
from(
select a.cashbilling_id,
a.article_id a_article_id,
b.article_id b_article_id,
b.cashbillingreturnarticle_total,
a.cashbillingbillarticle_total,
b.cashbillingreturn_id,
b.cashbillingreturn_date
from cash_billings_bills_articles a
left join cash_billings_returns_articles b on (a.cashbilling_id = b.cashbilling_id and a.article_id = b.article_id)
union
select b.cashbilling_id, a.article_id a_article_id, b.article_id b_article_id, b.cashbillingreturnarticle_total, a.cashbillingbillarticle_total, b.cashbillingreturn_id, b.cashbillingreturn_date
from cash_billings_bills_articles a
right join cash_billings_returns_articles b on (a.cashbilling_id = b.cashbilling_id and a.article_id = b.article_id)
) q join (select @min_id := null as m, @min_date := null as d, @group_id := null as g, @date_group_id := null as dg) v
order by cashbilling_id, -cashbillingreturn_id desc
) q
where min_cashbillingreturn_id is not null
order by cashbilling_id, cashbillingreturn_id, abs(diff)
;