2012-11-15 54 views
0

我有一個非常標準的查詢,將讓我有大於0SQL SUM,由基和具有查詢

這正常庫存產品的列表,但是我現在需要添加的所有負面的SUM給定SKU的BranchID 31的編號。

SELECT * FROM Products WHERE 
PrimaryPLU IN 
(select SKU FROM Stock 
WHERE BranchID IN (2,12,1,11,0,96,32,13,14,15) 
AND ApplicationID = @site 
GROUP BY SKU HAVING(SUM(Stock)) > 0)) 

SO BranchID 31可以有正數和負數,但我只需要得到該SKU消極因素的總和,這就需要添加到檢查,看它是否大於0

不知道從哪裏開始,希望得到來自SQL高手的支持!

在此先感謝!

戴夫

回答

1

試試這個:

SELECT * FROM Products WHERE 
PrimaryPLU IN 
(select SKU FROM Stock 
WHERE BranchID IN (2,12,1,11,0,96,31,32,13,14,15) 
AND ApplicationID = @site 
GROUP BY SKU HAVING(SUM(CASE WHEN Stock < 0 AND BranchID = 31 
       THEN Stock ELSE 0 END)) > 0)) 
+0

謝謝,但它不檢查BranchID 31,我想我需要類似於: SELECT * FROM Products WHERE PrimaryPLU IN (2,12,1,11,0,96,32,13,14,15 ) AND ApplicationID = @site GROUP BY SKU HAVING(SUM(Stock))+(SELECT SUM(stock)FROM Stock WHERE BranchID = 31 AND St​​ock <0 AND SKU = ????)> 0)) – dhardy

+0

Ah I看,謝謝! – dhardy

+0

我改了一下代碼,也許你可以在你的地方使用BranchID 31,但對於這個只使用正值 –

0

取負數的絕對值(股票)的總和,看看他們是非零。