【问题标题】:如何根据条件向现有 SQL Server 表添加列?
【发布时间】:2022-01-22 06:22:20
【问题描述】:

我想根据表中 3 列的条件向现有表中添加一列,如下例所示。

我有 3 列:

  • 已过期
  • 待定
  • on_the_go

其中每一列的值都是另一个表中对应值的 ID 号(过期值为 1)(待定值为 2)...

我想要添加一个名为 status 的列,将所有这 3 列合并为 1

我尝试使用CASE WHEN,但没有按预期工作:

SELECT 
    EXPIRED, pending, on_the_go,
    CASE EXPIRED
        WHEN 1 THEN 1
    END AS status_type,
    CASE pending
        WHEN 2 THEN 2
    END AS status_type,
    CASE on_the_go
        WHEN 3 THEN 3
    END AS status_type,
    COUNT(*) AS number_of_exchange_activities 
FROM 
    card 
GROUP BY 
    EXPIRED, pending, on_the_go
EXPIRED pending on_the_go status_type status_type status_type number_of_exchange_activities
0 2 0 NULL 2 NULL 550
0 0 3 NULL NULL 3 320
1 0 0 1 NULL NULL 310

这是我期望得到的:

EXPIRED pending on_the_go status_type number_of_exchange_activities
0 2 0 2 550
0 0 3 3 320
1 0 0 1 310

【问题讨论】:

  • 如果状态互斥,可以expired+pending+on_the_go as status_type
  • 好的答案谢谢

标签: sql sql-server select group-by case


【解决方案1】:

您可以使用case 的长格式,它允许您在每个when 子句中放置完整的条件:

SELECT   expired, pending, on_the_go,
         CASE WHEN expired = 1 THEN 1
              WHEN pending = 2 THEN 2
              WHEN on_the_go = 3 THEN 3
         END AS status_type,
         COUNT(*) AS number_of_exchange_activities 
FROM     card 
GROUP BY expired, pending, on_the_go

【讨论】:

    【解决方案2】:
    CASE  
        WHEN EXPIRED = 1 THEN 1 
        WHEN pending = 2 THEN 2 
        WHEN on_the_go = 3 THEN 3 
        ELSE 0
    END As 'status_type'
    

    【讨论】:

    • 请添加关于您的代码的说明。按edit 并更新您的答案。
    猜你喜欢
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    相关资源
    最近更新 更多