Question

I have a SELECT query and would like to place a negative sign in percentage value if it's less than 100. Here is my query:

SELECT produces, amount, percentage FROM inventory

I tried:

SELECT produces, amount, CASE WHEN percentage<100 THEN '-'+percentage ELSE percentage END FROM inventory

But it did not work.

Était-ce utile?

La solution 2

Since the percentage-column is a numeric of some sort, not a string, you need to cast it to a varchar, something like this should work:

SELECT produces, amount, CASE WHEN percentage < 100 THEN '-' + CAST(percentage AS varchar(50)) ELSE CAST(percentage AS varchar(50)) END FROM inventory

Here's a working example:

CREATE TABLE inventory (produces int, amount int, percentage int)

INSERT INTO inventory values(1, 1, 110)
INSERT INTO inventory values(2, 2, 100)
INSERT INTO inventory values(3, 3, 90)
INSERT INTO inventory values(4, 4, 80)

SELECT
    produces, 
    amount, 
    CASE 
        WHEN percentage < 100 
        THEN '-' + CAST(percentage AS varchar(50)) 
        ELSE CAST(percentage AS varchar(50)) 
    END
FROM
    inventory

Autres conseils

If you want to invert the sign simply multipy it with -1.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top