2017-05-10 14 views
0

私、このようなデータを持つテーブルという名前のソーステーブルを持っている: enter image description hereSQLのSELECTグループ化および減算

と私は製品名で、このグループのようになり、ステータスのプラスとマイナスを持つ行を差し引くクエリをしたい:

enter image description here

どのようにSQLクエリを行うには?ありがとう!その後、

+1

を試してみましたか?ヒント: 'GROUP BY'、' CASE'。 –

答えて

1

グループ製品によって、条件SUMを(使用)

select product, 
     sum(case when status = 'plus' then total else 0 end) - 
     sum(case when status = 'minus' then total else 0 end) as total, 
     sum(case when status = 'plus' then amount else 0 end) - 
     sum(case when status = 'minus' then amount else 0 end) as amount 
from your_table 
group by product 
1

別のものを持っているあなたが提供した特定のデータのために働くjoinを用いる方法、(「プラス」と一つの「マイナスがあります"製品ごとの行):

select tplus.product, (tplus.total - tminus.total) as total, 
     (tplus.amount - tminus.amount) as amount 
from t tplus join 
    t tminus 
    on tplus.product = tminus.product and 
     tplus.status = 'plus' and 
     tplus.status = 'minus'; 

このクエリと集計クエリは、提供したデータに対してうまく機能します。言い換えれば、この問題を解決する方法はいくつかあります(それぞれに長所があります)。

1

あなたは以下のように問い合わせることができます:あなたは何を

select product , sum (case when [status] = 'minus' then -Total else Total end) as Total 
    , sum (case when [status] = 'minus' then -Amount else Amount end) as SumAmount 
from yourproduct 
    group by product 
関連する問題