2016-04-12 11 views
1

私はqtyのフィールドとそれぞれのアイテムの購入または売却を示すフィールドを持つトランザクションを持つテーブルを持っています。テーブルに集約して0の値をスキップする必要があります

それぞれのアイテムの合計を示す集計クエリを作成しようとしています。

私のテーブルには、次のようになります。

ID Item  Qty Buy_sell price 
1  item1 5  1   2.5 
2  item1 4  0   3.2 
3  item2 8  1   155.25 
4  item3 179 1   89.75 
5  item1 18  1   3.1 
4  item3 179 0   93.25 

そして、私のクエリは次のようになります。これまでのところ

Select 
    Item, 
    sum(case when Buy_sell=1 then Qty when Buy_sell=0 then Qty*-1 else 0 end) as Balance 
from Table1 
group by Item 
order by Item 

とても良いです。

出力:

私はSQL ServerのCE上でこれをやってるの合計が0の行を避けたい
Item  Balance 
Item1 19 
Item2 8 
Item3 0 

答えて

3

あなたはHAVING句で条件を配置する必要があります。

Select Item, sum(case 
        when Buy_sell=1 then Qty 
        when Buy_sell=0 then Qty*-1 
        else 0 
      end) as Balance 
from Table1 
group by Item 
having sum(case 
       when Buy_sell=1 then Qty 
       when Buy_sell=0 then Qty*-1 
       else 0 
      end) <> 0 
order by Item 
+0

super ... thanks !!!! – user3129015

0

を派生テーブルにcaseの一部を行う、いくつかの入力を保存するには:

select Item, sum(Balance) as Balance 
from 
(
    select Item, case 
        when Buy_sell=1 then Qty 
        when Buy_sell=0 then Qty*-1 
        else 0 
       end as Balance 
    from Table1 
) dt 
group by Item 
having sum(balance) <> 0 
order by Item 

(ものリスクを減らすだろう入力エラー...)

+0

が合意しました!それを共有してくれてありがとう! – user3129015

関連する問題