查询其中一组记录的总和大于零
Query where sum of a group of records greater than ZERO
我正在尝试针对交易 table 编写查询,其中存在各种项目的买卖交易。尝试在给定日期构建一个查询,我想知道我持有多少每件物品。那部分实现了。
现在的问题是,我编写的查询 returns 曾经购买过并已售出的物品列表,因此在给定日期该物品显示余额为 0。我想避免在该特定日期之前余额为零的所有项目。
我的查询是这样的。
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
我试图修改添加Where TotalQty > 0
的where子句,但它不起作用。
不知道该怎么做。我正在尝试在 SQL Server CE 上构建它。
感谢您的帮助。
谢谢
尝试在 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
我正在尝试针对交易 table 编写查询,其中存在各种项目的买卖交易。尝试在给定日期构建一个查询,我想知道我持有多少每件物品。那部分实现了。
现在的问题是,我编写的查询 returns 曾经购买过并已售出的物品列表,因此在给定日期该物品显示余额为 0。我想避免在该特定日期之前余额为零的所有项目。
我的查询是这样的。
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
我试图修改添加Where TotalQty > 0
的where子句,但它不起作用。
不知道该怎么做。我正在尝试在 SQL Server CE 上构建它。
感谢您的帮助。
谢谢
尝试在 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