簡體   English   中英

查詢一組記錄的總和大於零

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

我試圖在一個交易表上寫一個查詢,其中有各種項目的買賣交易。 嘗試建立一個查詢,我希望在給定的日期知道每個項目中有多少個。 那部分實現了。

現在的問題是,我編寫的查詢返回了曾經購買和出售過的物品清單,因此在給定的日期該物品顯示為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子句,添加Where TotalQty > 0 ,但是它不起作用。

不確定如何處理。 我正在嘗試在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM