我有表prices
的表结构:
CREATE TABLE prices
(
id int,
priceFrom int,
priceUp int
);
INSERT INTO prices (id, priceFrom, priceUp)
VALUES (1, 23, 23), (2, 0, 0), (3, 12, 13),
(4, 40, 40), (5, 15, 15), (6, 0, 0);
结果如下:
我有这个问题:
select
pricefrom, priceup,
case
when pricefrom = 0 then null
when priceFrom <> priceUp then priceFrom + ' - ' + priceUp
when priceFrom = priceUp then priceFrom
end as FinalPrice
from
prices
我需要做的是
答案 0 :(得分:10)
我认为你在这里寻找 concat 功能。
select pricefrom, priceup,
case
when pricefrom = 0 then null
when priceFrom <> priceUp then concat(priceFrom, ' - ', priceUp)
when priceFrom = priceUp then cast(priceFrom as varchar(8))
end as FinalPrice
from prices
此链接可能会有所帮助
答案 1 :(得分:7)
您没有提供错误,但是按照CASE EXPRESSION
的格式我假设它因转换而丢失了错误。
您应该使用CAST to VARCHAR
:
select pricefrom, priceup,
case
when pricefrom = 0 then ''
when priceFrom <> priceUp then CAST(priceFrom as varchar(10)) + ' - ' + CAST(priceUp as varchar(10))
when priceFrom = priceUp then CAST(priceFrom as varchar(10))
end as FinalPrice
from prices
我不确定第一个WHEN
,但您应该知道:
通常CASE EXPRESSION
的第一个条件确定列的类型,因此,如果第一个THEN
放置一个整数,则此列将是一个整数。
因为你在其中放入了null值,我不确定该列将被评估为哪种类型,所以它仍然会抛出错误,但你可以尝试一下:
when pricefrom = 0 then null
注意:与@ aakashpugta.0205一样,使用CONCAT()
转换是自动的,但您应该知道自2012年以来{1}仅在SQL-Server上可用,所以在旧版本中不起作用!
让我再向你们提一篇关于CASE EXPRESSION secrets
的文章。
答案 2 :(得分:6)
您必须CAST
到VARCHAR
:
select pricefrom, priceup,
case
when pricefrom = 0 then null
when priceFrom <> priceUp then concat(cast(priceFrom as varchar(8)),
' - ',
cast(priceUp as varchar(8)))
when priceFrom = priceUp then cast(priceFrom as varchar(8))
end as FinalPrice
from prices
答案 3 :(得分:2)
您应该将价格字段转换为字符串,以便SQL了解您不希望将它们视为数字并进行数学运算:
select pricefrom, priceup,
case
when pricefrom = 0 then null
when priceFrom <> priceUp then cast(priceFrom as varchar) + ' - ' + cast(priceUp as varchar)
when priceFrom = priceUp then priceFrom
end as FinalPrice
from prices