0

I am trying to run a simple report where one of the columns is a float type, but I want to change the result to show a string (I think that is the best way). If the value of the float column is 101 or 201, I want the result to show as '101, 201' and other values to show as they are in the table.

This is what I've been messing with, but the results are incorrect:

SELECT float_column, 
CASE 
    WHEN (STR(float_column, 10, 16)) IN ('101', '201') THEN '101,201'
    ELSE column
END AS float_column, column2, column3
FROM database.table
ORDER BY float_column
3
  • 2
    MySQL or SQL Server? They are completely different. Probably you shouldn't be using a float in the first place - seems like you want an int. Commented Mar 30, 2021 at 23:01
  • What kind of strings will STR(float_column, 10, 16) produce? Have a look: learn.microsoft.com/en-us/sql/t-sql/functions/… Commented Mar 30, 2021 at 23:03
  • Just use numeric comparison and cast the output of all non 101,201 values Commented Mar 30, 2021 at 23:04

1 Answer 1

1

Why wouldn't you use number comparisons?

SELECT float_column, 
       CASE WHEN float_column in (101, 201) THEN '101,201'
            ELSE CAST(float_column as VARCHAR(255))
       END AS string_column, column2, column3
FROM database.table
ORDER BY float_column;

I don't usually advise equality comparisons for floats -- but the above could be adjusted by converting to an integer to numeric. I don't see what the conversion to the string is doing for you.

Sign up to request clarification or add additional context in comments.

3 Comments

I understand that OP did it first, but it's not a good idea to use float column both as a field and alias.
@PM77-1 just fix it when you see stuff like that, together lets leave best practise examples for all
Thank you!! This really helped me in the right direction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.