1

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

SELECT produces, amount, percentage FROM inventory

我试过:

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

但它没有用。

4

2 回答 2

2

如果要反转符号,只需将其乘以 -1。

于 2013-04-12T18:04:29.567 回答
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
于 2013-04-12T18:07:31.040 回答