表结构如下
一、交易流水表:transaction(一个订单可能有多笔流水)
id order_id jy_type amount
(流水ID (订单id) (交易类型) (交易金额)
1 1 0 200
2 1 1 180
3 1 0 50
交易类型:0:代表收款,1:代表付款
二、订单表:order
order_id receivable payable
(订单id) (应收总额) (应付总额)
1 300 200
需要统计出以下结果:
订单号 应收总额 已收 未收 应付总额 已付 未付
1 300 250 50 200 180 20
一、交易流水表:transaction(一个订单可能有多笔流水)
id order_id jy_type amount
(流水ID (订单id) (交易类型) (交易金额)
1 1 0 200
2 1 1 180
3 1 0 50
交易类型:0:代表收款,1:代表付款
二、订单表:order
order_id receivable payable
(订单id) (应收总额) (应付总额)
1 300 200
需要统计出以下结果:
订单号 应收总额 已收 未收 应付总额 已付 未付
1 300 250 50 200 180 20
解决方案
40
select a.order_id,b.receivable,a.received,(b.receivable-a.received),b.payable,a.pay,(b.payable-a.pay) from (select order_id,sum(if(jy_type = 0, 1, 0))received,sum(if(jy_type = 1, 1, 0))pay from `transaction` group by order_id)a,`order` b where a.order_id = b.order_id;
20
if(jy_type = 0, 1, 0)这种用法相似于三目运算符,if else的快捷写法。
想要正确的结果,这里应该是if(jy_type = 0, amount, 0)
select a.order_id,b.receivable,a.received,(b.receivable-a.received),b.payable,a.pay,(b.payable-a.pay) from (select order_id,sum(if(jy_type = 0, amount, 0))received,sum(if(jy_type = 1, amount, 0))pay from `transaction` group by order_id)a,`order` b where a.order_id = b.order_id;
20
SELECT a.订单号,a.应收总额,a.已收,a.未收,a.应付总额,b.已付,b.未付 FROM (SELECT b.order_id AS 订单号,b.receivable AS 应收总额,SUM(a.amount) AS 已收,(b.receivable-SUM(a.amount)) AS 未收,b.payable AS 应付总额 FROM `transaction` a INNER JOIN `order` b ON b.order_id = a.order_id AND a.jy_type = 0) a INNER JOIN (SELECT b.order_id AS 订单号,SUM(a.amount) AS 已付,(b.payable-SUM(a.amount)) AS 未付 FROM `transaction` a INNER JOIN `order` b ON b.order_id = a.order_id AND a.jy_type = 1) b ON a.订单号= b.订单号