简体   繁体   中英

MySQL statement with if and CONCAT

I have a table with 3 columns ID, Name, Floor and Ceiling. I need to build a select statement that either concats or doesn't the Floor and Ceiling values. If Floor and Ceiling are the same, then I need to just return Floor, but if they are different I want to concat the columns as a range column.

Here's example data:

ID | Name | Floor | Ceiling
---------------------------
1    name1  1       2
2    name2  5       5
3    name3  7       9

The statement should return the following:

ID | Name | Range
-----------------
1    name1  1-2
2    name2  5
3    name3  7-9

Here's my statement so far, what am I doing wrong?

SELECT name,
(CASE
 WHEN floor != ceiling THEN CONCAT(floor, '-', ceiling) AS range
 ELSE floor AS range
END)
FROM tablename

Any help would be appreciated!

Thanks!

You're close. You don't put AS range inside the CASE expression, you put it at the end.

SELECT name,
    CASE
    WHEN floor != ceiling THEN CONCAT(floor, '-', ceiling)
    ELSE floor
    END AS range
FROM tablename

You should put the alias range outside the CASE clause, like the following:

SELECT name,
(CASE
 WHEN floor != ceiling THEN CONCAT(floor, '-', ceiling)
 ELSE floor
END) AS range
FROM tablename;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM