我使用此代码试图获得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
我该怎么办?没有办法改变桌面。
答案 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值都是数字,则可以使用cast
或convert
:
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_cast
或try_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;