我在下面发布了这个问题并得到了一些回复。
How to display rows that when added together equal zero
最接近回答问题的答案是:
SELECT t1.*
FROM transactions AS t1
INNER JOIN
(
SELECT
tbis.client_ref ,
tbis.supplier_key,
sum(tbis.client_amount) AS total
FROM transactions tbis
WHERE tbis.client_amount !=0
GROUP BY tbis.client_ref, tbis.supplier_key
HAVING sum(tbis.client_amount) =0
) AS t2 ON t1.client_ref = t2.client_ref
AND t1.supplier_key = t2.supplier_key
ORDER BY t2.total;
我遇到的问题是它在结果中包含客户端数量为0的行。我基本上只需要在客户端数量不为0的行上执行以下操作。
有什么想法吗?
非常感谢
答案 0 :(得分:0)
看起来这个问题正在发生,因为您的交易表中没有主键(正如您在其他帖子中暗示的那样),或者您没有加入它。这意味着只要至少有一个client_ref
和supplier_key
对具有非零值,就会返回所有值。
向外部查询添加WHERE
SELECT t1.*
FROM transactions AS t1
INNER JOIN
(
SELECT
tbis.client_ref ,
tbis.supplier_key,
sum(tbis.client_amount) AS total
FROM transactions tbis
WHERE tbis.client_amount !=0
GROUP BY tbis.client_ref, tbis.supplier_key
HAVING sum(tbis.client_amount) =0
) AS t2 ON t1.client_ref = t2.client_ref
AND t1.supplier_key = t2.supplier_key
WHERE t1.client_amount !=0
ORDER BY t2.total;
或者加入client_amount
SELECT t1.*
FROM transactions AS t1
INNER JOIN
(
SELECT
tbis.client_ref ,
tbis.supplier_key,
sum(tbis.client_amount) AS total
FROM transactions tbis
WHERE tbis.client_amount !=0
GROUP BY tbis.client_ref, tbis.supplier_key
HAVING sum(tbis.client_amount) =0
) AS t2 ON t1.client_ref = t2.client_ref
AND t1.supplier_key = t2.supplier_key
AND t1.client_amount = t2.client_amount
ORDER BY t2.total;