【问题标题】:Adding a new column to an existing table based on the contents of two preexisting columns根据两个预先存在的列的内容向现有表添加新列
【发布时间】:2020-12-02 18:05:53
【问题描述】:

我正在尝试向 SQL Server 中的现有表添加新列。我希望根据表中两个现有列的内容来确定这个新列的值。例如,有一列称为制造商,另一列称为供应商。当这两列的内容相同时,我希望在新列中显示“相同”一词,如果两列的内容不同,我希望新列显示“不一样” .

以下语句可以向我显示我正在寻找的所有值,但我不知道如何根据这些结果添加如上所述的新列。我一直在论坛搜索,查看了Case语句,但没有任何成功。

Select *
from dbo.[Merchandise]
where [Manufacturer] = [Vendor]

任何帮助将不胜感激。

【问题讨论】:

    标签: sql sql-server case calculated-columns


    【解决方案1】:

    我可以使用以下方法添加带有条件的列。

     alter table TABLE_NAME
        add NEW_COL_NAME as (case 
            when COL1_NAME = COL2_NAME then 'same'
            else 'not the same'
            end);
    

    对于你来说,它可能会喜欢

     alter table Merchandise
        add NEW_COL_NAME as (case 
            when Manufacturer = Vendor then 'Same'
            else 'Not the Same'
            end);
    

    【讨论】:

      【解决方案2】:

      听起来像 case 表达式:

      select m.*,
             (case when manufacturor = vendor then 'Same' else 'Not the same' end) as newcolumn
      from merchandise;
      

      【讨论】:

        【解决方案3】:

        听起来你想要一个计算列:

        alter table marchandise
            add newcol 
            as (case when manufacturer = vendor then 'same' else 'not the same' end)
        ;
        

        这会在表中添加一个名为 newcol 的新列,其值是根据其他两列的值自动计算得出的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-09-29
          • 2015-11-19
          • 1970-01-01
          • 1970-01-01
          • 2013-01-18
          • 2018-08-13
          • 2019-08-20
          相关资源
          最近更新 更多