【问题标题】:sql create column based on other columns with existing valuessql 根据具有现有值的其他列创建列
【发布时间】:2018-06-29 07:37:51
【问题描述】:

我需要一些 t-sql 帮助来创建下表中的“Grp”列。基本上我需要创建一个列来说明值何时存在,如果它为空,则将其从“Grp”列中排除。该表是我需要的最终结果的示例(现在只存在 Col1、Col2、Col3)

【问题讨论】:

    标签: sql tsql


    【解决方案1】:

    使用一些带有STUFFCASE 表达式来删除前导-

    SELECT
        STUFF(
            (
                CASE WHEN T.Col1 IS NOT NULL THEN '-Col1' ELSE '' END +
                CASE WHEN T.Col2 IS NOT NULL THEN '-Col2' ELSE '' END +
                CASE WHEN T.Col3 IS NOT NULL THEN '-Col3' ELSE '' END 
            ),
            1, 1, ''),
        T.Col1,
        T.Col2,
        T.Col3
    FROM
        YourTable AS T
    

    【讨论】:

    • 案例表达式.
    【解决方案2】:

    你可以使用case when语句:

    select 
      left(t.Grp,len(Grp)-1) as Grp,
      t.col1,t.col2,t.col3
    from (    
      select col1, col2, col3,
        case when col1 is null then '' else 'col1-' +
        case when col2 is null then '' else 'col2-' +
        case when col3 is null then '' else 'col3-'
        as Grp
      from your_table
      ) t
    

    【讨论】:

    • 修复包含多个 else 的 case 语句
    • 案例表达式.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2023-03-17
    • 2013-03-12
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多