如何在不向SQL中的表添加新列的情况下使用CASE

时间:2015-02-05 12:33:36

标签: sql sql-server sql-server-2012

如何根据条件更改CASE命令的列值而不向表中添加新列?

我知道的唯一方法是添加新列:

SELECT 
    t1.*
    ,CASE
        what='costs' THEN amount*(-1)
    ELSE
    sales
    END AS NewAmount
FROM t1

有没有办法得到如下图所示的结果?请注意,有时条件由多个列中的值指定(what = costs AND country = Atlantida)

case

3 个答案:

答案 0 :(得分:4)

只选择您想要的列:

SELECT t1.what, 
       (CASE WHEN what = 'costs' THEN amount*(-1)
             ELSE sales
        END) AS Amount
FROM t1

答案 1 :(得分:3)

是的,有办法, 而不是select *,而只使用必需的列名。

SELECT 
    t1.what
    ,CASE
        WHEN what='costs' THEN amount*(-1)
    ELSE
    sales
    END AS Amount
FROM t1

答案 2 :(得分:0)

不花费金额

SELECT 
    t1.*
    ,CASE when what='costs' THEN amount*(-1)
     ELSE
        amount
     END AS NewAmount
FROM t1