在值中放置一个负号

时间:2013-04-12 18:01:27

标签: sql select negative-number

我有一个SELECT查询,如果它小于100,我想在百分比值中放置一个负号。这是我的查询:

SELECT produces, amount, percentage FROM inventory

我试过了:

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

但它不起作用。

2 个答案:

答案 0 :(得分:2)

如果要反转符号,请将其简化为-1。

答案 1 :(得分:1)

由于百分比列是某种数字,而不是字符串,您需要将其强制转换为varchar,这样的事情应该有效:

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

这是一个有效的例子:

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