2016-04-16 16 views
0

は、私は3つの列からテーブルの合計を返すSQLクエリを持っており、これが私のクエリで偽となる場合は、ゼロにクエリの結果を設定する方法:その条件は

SELECT c.*, 
    (select sum(t.incoming) - sum(t.outgoing) from transactions t where t.client_id = c.id and currency = 'Dollar') + 
    (select sum(t.equal_to_dollar) from transactions t where t.incoming != 0 and currency != 'Dollar' and t.client_id = c.id) - 
    (select sum(t.equal_to_dollar) from transactions t where t.outgoing != 0 and currency != 'Dollar' and t.client_id = c.id) 
as total from clients c 

私の問題は、のとき1であります2番目と3番目の条件(内部選択)が満たされない場合、null値が返され、select全体がnullになります。 null値は任意の値で加算または減算できないためです。
私は、その条件がfalseに評価されるので、全体のクエリには影響を及ぼさず、クエリはwhere節の条件を満たす部分の値を返すように、クエリの結果を設定する方法はありますか?
と私は結果が重要で、それはとても正確でなければならないとき、それは価値の計算の良い方法ですか?
と私はあなたの助けを事前に感謝したいと思う:)

+0

可能な複製をhttp://stackoverflow.com/questions/5697942/select-one-column([その他がnullの場合は、1つの列を選択] -if-the-other-is-null)(あるいはおそらく[フィールドがMySQLでnullの場合は0を返す](http://stackoverflow.com/questions/3997327/return-0-if-field-is-null-in -mysql)) –

答えて

1

あなただけcoalesce()を使用することができます。

select c.*, 
     ((select coalesce(sum(t.incoming), 0) - coalesce(sum(t.outgoing), 0) from transactions t where t.client_id = c.id and currency = 'Dollar') + 
     (select coalesce(sum(t.equal_to_dollar), 0) from transactions t where t.incoming <> 0 and currency <> 'Dollar' and t.client_id = c.id) - 
     (select coalesce(sum(t.equal_to_dollar), 0) from transactions t where t.outgoing <> 0 and currency <> 'Dollar' and t.client_id = c.id) 
     ) as total 
from clients c ; 

各サブクエリはgroup byのない集合体であるので、各々が1つの行を返します - これ、一致するものがなければ、NULLの値を持ちます。 COALESCE()はそれを0に変換します。

ただし、3つのサブクエリの理由はありません。ただ一つのサブクエリを使用して、条件付きの集約使用して計算を行いますの

select c.*, 
     (select sum(case when currency = 'Dollar' 
         then coalesce(t.incoming, 0) - coalesce(t.outgoing, 0) 
         when t.incoming <> 0 
         then coalesce(t.equal_to_dollar, 0) 
         when t.outgoing <> 0 
         then - coalesce(t.equal_to_dollar, 0) 
         else 0 
        end) 
     from transactions t 
     where t.client_id = c.id 
     ) as total 
from clients c ; 
+0

ありがとう、それはうまく働いています – AliDK

+0

私はどのように私が書く方法で2つの条件をチェックすることができます教えてくれますか?このメソッドの詳細については、 – AliDK

+0

@AliDKのリンクを記述してください。 。 。私はあなたが何を意味するか分からない。おそらく別の質問をする必要があります。 –