简体   繁体   English

如何根据条件向现有的 SQL 服务器表添加列?

[英]How to add column to an existing SQL Server table based on condition?

I want to add a column to an existing table based on the condition of 3 columns in the table like the example below.我想根据表中 3 列的条件向现有表中添加一列,如下例所示。

I have 3 columns:我有 3 列:

  • EXPIRED已到期
  • pending待办的
  • on_the_go在旅途中

where each column had as value the ID number from another table of the corresponding value (expired value is 1)(pending value is 2)...其中每一列的值都是来自另一个表的对应值的 ID 号(过期值为 1)(待定值为 2)...

What I want is to add a column called status that combine all these 3 columns into 1我想要的是添加一个名为status的列,将所有这 3 列合并为 1

I tried to use CASE WHEN but that did not work as expected:我尝试使用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 number_of_exchange_activities
0 0 2 2 0 0 NULL NULL 2 2 NULL NULL 550 550
0 0 0 0 3 3 NULL NULL NULL NULL 3 3 320 320
1 1 0 0 0 0 1 1 NULL NULL NULL NULL 310 310

This is what I expected to get:这是我期望得到的:

EXPIRED已到期 pending待办的 on_the_go在旅途中 status_type状态类型 number_of_exchange_activities number_of_exchange_activities
0 0 2 2 0 0 2 2 550 550
0 0 0 0 3 3 3 3 320 320
1 1 0 0 0 0 1 1 310 310

You can use the long form of case that allows you to place full conditions in each when clause:您可以使用长形式的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
CASE  
    WHEN EXPIRED = 1 THEN 1 
    WHEN pending = 2 THEN 2 
    WHEN on_the_go = 3 THEN 3 
    ELSE 0
END As 'status_type'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM