SQL 当条件为真时,Case 语句应用 else 子句
SQL Case statement applies else clause when condition is true
当我 运行 以下 sql 查询语句时,它的格式不是数字 (10,0)
但是数字(10,3)。
如果我将 cast(Oct as numeric(10,3)) 替换为 null 它就可以了。
select case when col='Gallons'
then cast(Oct as numeric(10,0))
else cast(Oct as numeric(10,3))
end as Oct
from (select 'Gallons' as col, 225.00 as Oct) a
为什么会这样?
一个case
表达式returns一个类型。它必须在 numeric(10, 0)
和 numeric(10, 3)
之间做出决定。后者比较笼统,所以会选择那个。
如果你想控制结果集的样子,然后将值转换为字符串:
select (case when col = 'Gallons'
then cast(cast(Oct as numeric(10, 0)) as varchar(255))
else cast(cast(Oct as numeric(10, 3)) as varchar(255))
end) as Oct
from (select 'Gallons' as col, 225.00 as Oct) a
您也可以使用 str()
函数执行此操作。
要保留这两种格式,您可以将数值转换为 varchar:
select case when col='Gallons' then cast(cast(Oct as numeric(10,0)) as varchar(max))
else cast(cast(Oct as numeric(10,3)) as varchar(max)) end as Oct
from (select 'Gallons' as col, 225.00 as Oct union all select 'Other' as col, 123.45 as Oct) a
结果:
当我 运行 以下 sql 查询语句时,它的格式不是数字 (10,0)
但是数字(10,3)。
如果我将 cast(Oct as numeric(10,3)) 替换为 null 它就可以了。
select case when col='Gallons'
then cast(Oct as numeric(10,0))
else cast(Oct as numeric(10,3))
end as Oct
from (select 'Gallons' as col, 225.00 as Oct) a
为什么会这样?
一个case
表达式returns一个类型。它必须在 numeric(10, 0)
和 numeric(10, 3)
之间做出决定。后者比较笼统,所以会选择那个。
如果你想控制结果集的样子,然后将值转换为字符串:
select (case when col = 'Gallons'
then cast(cast(Oct as numeric(10, 0)) as varchar(255))
else cast(cast(Oct as numeric(10, 3)) as varchar(255))
end) as Oct
from (select 'Gallons' as col, 225.00 as Oct) a
您也可以使用 str()
函数执行此操作。
要保留这两种格式,您可以将数值转换为 varchar:
select case when col='Gallons' then cast(cast(Oct as numeric(10,0)) as varchar(max))
else cast(cast(Oct as numeric(10,3)) as varchar(max)) end as Oct
from (select 'Gallons' as col, 225.00 as Oct union all select 'Other' as col, 123.45 as Oct) a
结果: