[英]ISNULL with PIVOT in SQL
With pivot, I need to replace all null values and 0 values with a dash. 使用数据透视,我需要用破折号替换所有空值和0值。 I started with getting rid of null values: 我从摆脱空值开始:
SELECT FunctionCode, ISNULL(Col1, '-') AS Col1, ISNULL(Col2, '-') AS Col2
FROM
(
SELECT Company, FunctionCode, [Count]
FROM MyTable
) AS D
PIVOT
(
SUM([Count])
FOR Company IN (Col1, Col2)
) PIV;
For some reason, NULL is replaced with 0 instead of '-'. 由于某些原因,NULL被0代替而不是'-'。 Could you please help? 能否请你帮忙?
Thanks. 谢谢。
SUM()
can only operate on the numeric data types. SUM()
只能对数字数据类型进行操作。
The numeric data types have a higher precedence than any textual data type 1 . 数字数据类型的优先级高于任何文本数据类型1 。
So the -
is converted to a number, eg: 因此, -
转换为数字,例如:
select CONVERT(int,'-')
Produces the result 0
. 产生结果0
。
So, the solution is to convert your values to a textual type. 因此,解决方案是将您的值转换为文本类型。
SELECT FunctionCode, ISNULL(CONVERT(varchar(10),Col1), '-') AS Col1,
ISNULL(CONVERT(varchar(10),Col2), '-') AS Col2
...
And with 0
s dealt with also: 并且用0
s处理:
SELECT FunctionCode, ISNULL(CONVERT(varchar(10),NULLIF(Col1,0)), '-') AS Col1,
ISNULL(CONVERT(varchar(10),NULLIF(Col2,0)), '-') AS Col2
...
1 This doesn't, technically, matter here because ISNULL
doesn't follow the type rules - it always tries to convert its second argument to the same type as the first. 1这在技术上并不重要,因为ISNULL
不遵循类型规则-它总是尝试将其第二个参数转换为与第一个参数相同的类型。 But since the problem is the type of the first argument, the same fix applies. 但是由于问题是第一个参数的类型,因此适用相同的解决方法。
Precedence would have mattered were we to be using COALESCE
instead of ISNULL
, which is usually preferred. 如果我们要使用COALESCE
而不是通常首选的ISNULL
,那么优先级会很重要。
Here is example: 这是示例:
When INT
type column set dash, then it becomes 0: 当INT
类型列设置破折号时,则变为0:
SELECT ISNULL( CAST(NULL AS INT), '-' )
But if we CAST
it to some VARCHAR
then it is normal dash : 但是,如果我们CAST
它一些VARCHAR
那么它是正常的破折号:
SELECT ISNULL( CAST( CAST(NULL AS INT) AS VARCHAR(100)), '-' )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.