我有一个名为cash_billings_bills_articles
的表格,其中包含原始发票中的项目,另一个cash_billings_returns_articles
保存新的更改历史记录发票或退款。
cash_billings_bills_articles
数据:
cash_billings_returns_articles
数据:
有什么想法吗?感谢
SQL小提琴:SQL Fiddle Demo
更新
答案 0 :(得分:2)
这是一个查询,它将获得问题中显示的结果集。但是,业务规则可能无法完全实现,因为很难从输出中解读。此外,这可能最好用过程语言完成,因为它需要跨行进行一些计算。
它使用左右外连接和union来获取两个表中的所有行。
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)
;