计算两个表中两个不同列之和的差值

时间:2012-01-10 02:17:05

标签: mysql

我有三个不同的表,名为CASHIER,SALES和REFUNDS

CASHIER表有:

  

cashierID / cashier_name

SALES表有:

  

salesID / cashierID / amountReceived

REFUNDS表有:

  

refundsID / cashierID / amountRefunded

我想分别通过amountReceived和amountRefunded列显示从销售和退款中收到的收银员总金额。会有一个mysql语法吗?非常感谢!

2 个答案:

答案 0 :(得分:1)

select 
    c.cashierID,
    c.cashier_name,
    sum(s.amountReceived) as totalReceived,
    sum(r.amountRefunded) as totalRefunded
from CASHIER c
left join SALES s on s.cashierID = c.cashierID
left join REFUNDS r on r.cashierID = c.cashierID
group by 1,2

答案 1 :(得分:1)

SELECT c.cashier_name AS cashier, 
    COALESCE( salesByCashier.totalSales, 0 ) AS sales,
    COALESCE( refundsByCashier.totalRefunded, 0 ) AS refunds,
    COALESCE( salesByCashier.totalSales, 0 ) - 
      COALESCE( refundsByCashier.totalRefunded, 0  ) AS total
FROM
  cashier c
LEFT JOIN
   ( SELECT s.cashierID AS cashierID, SUM(amountReceived) AS totalSales
     FROM sales s
     GROUP BY s.cashierID ) salesByCashier
ON c.cashierID = salesByCashier.cashierID
LEFT JOIN
   ( SELECT r.cashierID AS cashierID, SUM(amountRefunded) AS totalRefunded
     FROM refunds r
     GROUP BY r.cashierID ) refundsByCashier
ON c.cashierID = refundsByCashier.cashierID