在 table 上聚合但需要跳过 0 个值

Aggregate on the table but need to skip 0 values

我有一个 table 交易,其中有一个字段表示数量,另一个字段表示相应商品是买入还是卖出。

我正在尝试编写一个聚合查询,为我提供每一项的总和。

我的 table 看起来像这样:

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

到目前为止一切顺利。

输出:

Item     Balance
Item1    19 
Item2    8
Item3    0

我想避免 Total 为 0 的行。我在 SQL 服务器 CE 上执行此操作。

您必须在 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

为了节省一些输入,在派生的 table:

中执行 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

(还将降低输入错误的风险...)