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

How to use CASE without adding new column to table in SQL

如何根据条件通过 CASE 命令更改列值而不给 table 添加新列?

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

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

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

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

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

Select 只是您想要的列:

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

你不想要数量不花钱吗?

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