2013-10-10 51 views
0

我發佈了下面的問題並得到了一些回覆。在SQL中限制返回的數據

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

*** *** SQL只是*結構化查詢語言* - 許多數據庫系統中使用的語言,但不是數據庫產品...很多東西都是特定於供應商的 - 所以我們真的需要知道您使用的數據庫系統**(以及哪個版本)(請相應地更新標籤).... –

回答

0

它看起來像發生此問題,因爲無論有關於您的交易表上沒有主鍵(在你的其他職位暗示),或者你不加入就可以了。這意味着只要至少有一個client_refsupplier_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; 
+0

Genius !選項1已經對問題進行了整理。您當時的看法是我沒有加入主鍵,因爲我必須爲每個客戶獲得總數。非常感謝! – chris1982