Case when a value is different to other value, SQL Server

可紊 提交于 2019-12-03 22:16:33
aakashgupta.0205

I think you're looking for the concat function here.

 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

This link will probably be helpful

MySQL combine two columns into one column

You didn't provide the error, but by the format of your CASE EXPRESSION I'm assuming it's throwing an error due to conversion.

You should use 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

I'm not sure about the first WHEN , but you should know that :

usually the first condition of a CASE EXPRESSION will determine the type of the column, so, if the first THEN placing an integer, this column will be an integer.

since you are putting null value in it, I'm not sure which type the column will be evaluated to, so it can still throw an error, but you can give it a try :

           when pricefrom = 0 then null

Note: Like @aakashpugta.0205 answer, using CONCAT() the convertion is automatic, but you should know that CONCAT() is available on SQL-Server only since 2012, so in older versions that won't work!

Let me also reffer you to an intersting article about CASE EXPRESSION secrets .

You have to CAST to 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

You should cast the price fields as string so that SQL understands that you don't want to treat them as numbers and do a mathematical operation:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!