简体   繁体   English

查询一组记录的总和大于零

[英]Query where sum of a group of records greater than ZERO

I am trying to write a query on a trades table where there are buy and sell transactions for various items. 我试图在一个交易表上写一个查询,其中有各种项目的买卖交易。 Trying to build a query where on a given date I wish to know how many of each item do I hold. 尝试建立一个查询,我希望在给定的日期知道每个项目中有多少个。 That part is achieved. 那部分实现了。

Now the issue is, the query I have written returns a list of items which were once bought, and sold already, so on a given date that item shows 0 as balance. 现在的问题是,我编写的查询返回了曾经购买和出售过的物品清单,因此在给定的日期该物品显示为0作为余额。 I want to avoid all items with zero balance as of that particular date. 我要避免在该特定日期之前余额为零的所有项目。

My query looks like this. 我的查询看起来像这样。

Select 
    I.itemName, I.iID, 
    sum(case when Tr.Buy=1 then Tr.qty when Tr.Buy=0 then Tr.qty*-1 else 0 end) as TotalQty 
from 
    Trades Tr, ItemMast I
where 
    Tr.iID = I.iID 
    and I.iCode = '1253'
    and Tr.tDate <= '5/13/2015' 
group by 
    I.itemName, I.iID
order by 
    I.itemName, I.iID

I tried to modify the where clause adding Where TotalQty > 0 , but it does not work. 我试图修改where子句,添加Where TotalQty > 0 ,但是它不起作用。

Not sure how to go about with this. 不确定如何处理。 I am trying to build this on SQL Server CE. 我正在尝试在SQL Server CE上构建它。

Appreciate your help. 感谢您的帮助。

Thanks 谢谢

Try use full expression in having clause as below 尝试在having子句中使用完整表达式,如下所示

Select I.itemName, I.iID, sum(case when Tr.Buy=1 then Tr.qty when Tr.Buy=0 then Tr.qty*-1 else 0 end) as TotalQty 
from Trades Tr,ItemMast I
where Tr.iID = I.iID 
and I.iCode = '1253'
and Tr.tDate<= '5/13/2015' 
group by I.itemName, I.iID
having sum(case when Tr.Buy=1 then Tr.qty when Tr.Buy=0 then Tr.qty*-1 else 0 end) > 0
order by I.itemName, I.iID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM