문제

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