SQL Server - Include NULL using UNPIVOT

前端 未结 7 1576
暖寄归人
暖寄归人 2020-12-09 03:40

UNPIVOT will not return NULLs, but I need them in a comparison query. I am trying to avoid using ISNULL the following ex

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 04:05

    To preserve NULLs, use CROSS JOIN ... CASE:

    select a.ID, b.column_name
    , column_value = 
        case b.column_name
          when 'col1' then a.col1
          when 'col2' then a.col2
          when 'col3' then a.col3
          when 'col4' then a.col4
        end
    from (
      select ID, col1, col2, col3, col4 
      from table1
      ) a
    cross join (
      select 'col1' union all
      select 'col2' union all
      select 'col3' union all
      select 'col4'
      ) b (column_name)
    

    Instead of:

    select ID, column_name, column_value
    From (
      select ID, col1, col2, col3, col4
      from table1
      ) a
    unpivot (
      column_value FOR column_name IN (
        col1, col2, col3, col4)
      ) b
    

    A text editor with column mode makes such queries easier to write. UltraEdit has it, so does Emacs. In Emacs it's called rectangular edit.

    You might need to script it for 100 columns.

提交回复
热议问题