2017-05-10 6 views
0

Ich habe Tabelle mit dem Namen Quelltabelle mit Daten wie folgt aus: enter image description hereSQL-Select-Gruppierung und subtrahieren

und ich möchte Abfrage zu tun, die Zeile mit dem Status plus und minus subtrahiert wie diese Gruppe nach Produktnamen zu sein:

enter image description here

Wie das in SQL-Abfrage zu tun? Vielen Dank!

+1

Was haben Sie versucht? Tipp: 'GROUP BY',' CASE'. –

Antwort

1

Gruppe durch das Produkt und dann eine bedingte 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

Es gibt eine andere Methode join verwenden, die für die jeweiligen Daten arbeiten Sie zur Verfügung gestellt hat (was ein „plus“ hat und ein „Minus "Zeile pro Produkt):

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'; 

Sowohl diese als auch die Aggregationsabfrage funktionieren gut für die von Ihnen bereitgestellten Daten. Mit anderen Worten, es gibt mehrere Möglichkeiten, dieses Problem zu lösen (jedes hat seine Stärken).

1

Sie kann wie folgt abfragen:

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