Esraa_92 Esraa_92 - 5 months ago 9
SQL Question

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

I have this table structure for table

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);


This is the result:

enter image description here

I have this query:

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


what I need is to do a case when


  1. pricefrom = 0 then show null

  2. pricefrom = priceup then show the price

  3. At least if pricefrom != priceup I want to show for example this: 12(pricefrom) - 13(priceup)



but in my query in this line:

enter image description here

I try to do this with
<>
but in the result appears the sum for both numbers:

enter image description here

How can I fix this?

Answer

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

Comments