2013-10-14 60 views
0

如果我單獨運行的每一行我有這個疑問錯誤轉換VARCHAR到數字在SQL減查詢

select SUM(quantity) from Sales join Document on Sales.IdDocument = Document.IdDocument where (IdTipoDocumento = 'vco' or IdTipoDocumento = 'vcr') and IdArticulo = '01-00321' and IdListaEmpresa = 1000129 
- 
(select SUM(quantity) from Sales join Document on Sales.IdDocument = Document.IdDocument where IdTipoDocumento = 'dco' and IdArticulo = '01-00321' and IdListaEmpresa = 1000129) 

,每個查詢工作正常(第一次給了419,結果,第二個380),但如果我嘗試運行整個事情來獲得結果(419-380)它告訴我「將數據類型varchar轉換爲數字時出錯」。

他們都應該已經是數字(數量字段是整數類型反正),所以我不知道爲什麼錯誤出來......

+0

什麼是你的錯誤號碼? –

+0

@MuhammedAli Msg 8114,Level 16,State 5,Line 1 – ConnorU

+0

「IdListaEmpresa」的數據類型是什麼? – RBarryYoung

回答

1

方法1:

SELECT 
(select SUM(quantity) from Sales join Document on Sales.IdDocument = Document.IdDocument 
where (IdTipoDocumento = 'vco' or IdTipoDocumento = 'vcr') and IdArticulo = '01-00321' and 
IdListaEmpresa = 1000129) 

- 
(select SUM(quantity) from Sales join Document on Sales.IdDocument = Document.IdDocument 
where IdTipoDocumento = 'dco' and IdArticulo = '01-00321' and IdListaEmpresa = 1000129) 

方法2:

SELECT SUM(SQ) 
FROM (
SELECT CASE WHEN (IdTipoDocumento = 'vco' or IdTipoDocumento = 'vcr') THEN SUM(Quantity) 
WHEN IdTipoDocumento = 'dco' THEN -1*SUM(Quantity) 
END AS SQ 
FROM Sales join Document on Sales.IdDocument = Document.IdDocument 
where (IdTipoDocumento IN ('vco', 'vcr','dco')) and IdArticulo = '01-00321' and 
IdListaEmpresa = '1000129' 
GROUP BY IdTipoDocumento) AS T1 

方法3:

SELECT SUM(CASE WHEN IdTipoDocumento IN ('vco', 'vcr') THEN Quantity ELSE -1*Quantity END) 
AS SQ 
FROM Sales join Document on Sales.IdDocument = Document.IdDocument 
where (IdTipoDocumento IN ('vco', 'vcr','dco')) and IdArticulo = '01-00321' and 
IdListaEmpresa = 1000129 

方法3A:

SELECT IdListaEmpresa, 
     SUM(CASE WHEN IdTipoDocumento IN ('vco', 'vcr') 
        THEN Quantity 
        ELSE -1*Quantity END) AS SQ 
    FROM Sales join Document on Sales.IdDocument = Document.IdDocument 
    WHERE (IdTipoDocumento IN ('vco', 'vcr','dco')) 
     AND IdArticulo = '01-00321' 
     AND IdListaEmpresa IN (1000129, 1000130, 1,2,3,4,5) 
    GROUP BY IdListaEmpresa 
+0

同樣的錯誤。我認爲它可能會將每個總和(數量)的結果保存爲變量而不是數字? – ConnorU

+0

你可以更新你的sql語句添加單引號到IdListaEmpresa像'IdListaEmpresa ='1000129'' –

+0

我試過了。沒有區別,錯誤依然存在,IdListaEmpresa是數字反正... – ConnorU