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.

有帮助吗?

解决方案 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

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top