在MySQL中选择相关的行

时间:2016-03-14 02:18:09

标签: mysql sql

让我详细说明一下。我有一个这样的表(更新以包含更多示例)

| id | date      | cust | label                   | paid | due   |
+----+-----------+------+-------------------------+------+-------+
|  1 |2016-02-02 |    1 | SALE: Acme Golf Balls   |    0 |  1000 |
| 20 |2016-03-01 |    1 | PAYMENT: transaction #1 |  700 |     0 |
| 29 |2016-03-02 |    1 | PAYMENT: transaction #1 |  300 |     0 |
| 30 |2016-03-02 |    3 | SALE: Acme Large Anvil  |  500 |   700 |
| 32 |2016-03-02 |    3 | PAYMENT: transaction #30|  100 |     0 |
| 33 |2016-03-03 |    2 | SALE: Acme Rockets      |    0 |  2000 |

现在我需要输出一个表格,显示尚未全额支付的销售额和剩余金额。我怎么做?关于如何关联同一个表中的行的信息不多。

编辑:这是我想要制作的输出表

Table: debts_n_loans
| cust | label                  | amount |
==========================================
|    3 | SALE: Acme Large Anvil |    100 |
|    2 | SALE: Acme Rockets     |   2000 |

3 个答案:

答案 0 :(得分:1)

如果cust是将它们联系在一起的关键,那么您可以使用aggregationhaving子句:

select cust, sum(paid), sum(due)
from t
group by cust
having sum(paid) <> sum(due);

如果您需要详细信息,可以使用joininexists获取详细信息。

编辑:

如果您需要使用字符串末尾的事务执行此操作:

select t.id, t.due, sum(tpay.paid) as paid
from t left join
     t tpay
     on tpay.label like '%#' || t.id
where t.label like 'SALE:%' and
      tpay.label like 'PAYMENT:%'
group by t.id, t.due
having t.due <> sum(tpay.paid);

答案 1 :(得分:0)

所以你只需要大于0的行

SELECT * FROM <table> WHERE due > 0;

答案 2 :(得分:0)

试试这个:

SELECT 
    cust, 
    SUM(due) - SUM(paid) AS remaining
FROM t1
GROUP BY cust
HAVING SUM(due) > SUM(paid);