SQL:Varchar对Sum运算符无效

时间:2016-09-25 06:53:25

标签: sql sql-server tsql

我使用此代码试图获得4,202和&的总和。 203但是它还给我错误

SELECT *
FROM
( SELECT id,fieldNumber,fieldData FROM iso_fields) AS SourceTable
PIVOT
(
 SUM(fieldData) 
FOR fieldNumber IN ([4],[202],[203])
) AS PivotTable;

错误:

Operand data type varchar is invalid for sum operator.

原因:

Table using varchar instead of int

我该怎么办?没有办法改变桌面。

2 个答案:

答案 0 :(得分:3)

fieldData的数据类型为varchar,因此错误。如果fieldData列没有任何varchar数据,那么您可以在INT源查询中进行显式转换为pivot

SELECT *
FROM
( SELECT id,fieldNumber, fieldData FROM iso_fields) AS SourceTable
PIVOT
(
 MAX(fieldData) 
FOR fieldNumber IN ([4],[202],[203])
) AS PivotTable;

答案 1 :(得分:1)

如果您确保所有fieldData值都是数字,则可以使用castconvert

SELECT *
FROM
( SELECT id,fieldNumber,fieldData FROM iso_fields) AS SourceTable
PIVOT
(
SUM(cast(fieldData as int)) 
FOR fieldNumber IN ([4],[202],[203])
) AS PivotTable;

但是如果不确保fieldData中的数值,可以使用try_casttry_convert(SQL Server 2012及更高版本):

SELECT *
FROM
( SELECT id,fieldNumber,fieldData FROM iso_fields) AS SourceTable
PIVOT
(
SUM(try_cast(fieldData as int))
FOR fieldNumber IN ([4],[202],[203])
) AS PivotTable;