获取MySQL表之间的差异

时间:2016-10-22 23:35:30

标签: mysql sql select

今天我需要将两个表中的差异结合起来,这是我的情景。

enter image description here

我需要的结果如下:

enter image description here

我尝试了以下SQL,但我无法获得上面所需的结果:

SELECT
    Billings_Returns.billingreturn_id,
    Billings_Returns.billin_id,
    (Billings_Returns.billingreturn_total - Billings_Bills.billingbill_total) AS billingreturn_total
FROM Billings_Returns
LEFT JOIN Billings_Bills USING (billing_id) 

2 个答案:

答案 0 :(得分:2)

SELECT billingreturn_id,
       billing_id,
       - LAG( billingreturn_total, 1 ) OVER ( PARTITION BY billing_id ORDER BY billingreturn_id ) + billingreturn_total AS billingreturn_total
  FROM
     (    SELECT
                Billings_Returns.billingreturn_id,
                Billings_Returns.billing_id,
                ( Billings_Returns.billingreturn_total -  
                  Billings_Bills.billingbill_total
                ) AS billingreturn_total
          FROM Billings_Returns
         INNER JOIN 
               Billings_Bills U
            USING (billing_id); 
    ) Z;

以上查询将产生以下输出:

billingreturn_id | billingid | billingreturn_total
1                | 1         | -30
2                | 2         | -5
3                | 2         | -25
4                | 2         | 5

答案 1 :(得分:0)

感谢@Teja,解决了查询:

SET @total=0;
SET @billingid=0;
SELECT billingreturn_id,
       billing_id,
       IF(billing_id = @billingid, (billingreturn_total + (@total * -1)), billingreturn_total) AS billingreturn_total, @total:=billingreturn_total AS curr_quote, @billingid:=billing_id AS curr_billingid
FROM
 (    SELECT
            billings_Returns.billingreturn_id,
            billings_Returns.billing_id,
            ( billings_returns.billingreturn_total -  
              billings_bills.billingbill_total
            ) AS billingreturn_total
      FROM billings_returns
      INNER JOIN 
           billings_Bills
        USING (billing_id)
) billings_returns;