在SQL中将varchar转换为numeric减去查询时出错

时间:2013-10-14 15:05:50

标签: sql-server

我有这个查询

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转换为数字。“

他们都应该已经是数字(数量字段仍然是整数类型)所以我不知道为什么错误会出来......

1 个答案:

答案 0 :(得分: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