2017-05-10 69 views
0

我有這樣的數據表指定的源表: enter image description hereSQL選擇分組和減去

,我想這樣做查詢減去行與狀態加號和減號是這樣的組按照產品名稱:

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