【问题标题】:columns to rows maintaining userid维护用户 ID 的列到行
【发布时间】:2013-07-11 16:45:37
【问题描述】:

我的列看起来像这样:

UserID    col1    col2    col3    col4
---------------------------------------
233432    45.2    34.2    ''      0.52

我希望它看起来像这样:

UserID    colID    value
-------------------------
233432    col1     45.2
233432    col2     34.2
233432    col3     ''
233432    col4     0.52

我在下面找到了这个链接:

column to row in sql server?

但它并没有真正回答我的问题。我的问题。我正在使用 Sql Server 2012。

【问题讨论】:

    标签: sql sql-server unpivot


    【解决方案1】:

    由于您使用的是 SQL Server 2008+,因此您可以使用 CROSS APPLY 和 VALUES 来取消透视数据:

    select t.userid,
      c.colid,
      c.value
    from yourtable t
    cross apply
    (
      values
      ('col1', col1),
      ('col2', col2),
      ('col3', col3),
      ('col4', col4)
    ) c (colid, value);
    

    见SQL Fiddle with Demo

    【讨论】:

      【解决方案2】:
      Select UserID,'col1',col1 as 'value' from mytable
      union
      Select UserID,'col2',col2 from mytable
      union
      Select UserID,'col3',col3 from mytable
      union
      Select UserID,'col4',col4 from mytable
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-12
        • 2012-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-08
        相关资源
        最近更新 更多