【问题标题】:How to pivot two columns in SQL Server?如何在 SQL Server 中旋转两列?
【发布时间】:2020-03-22 13:55:00
【问题描述】:

我有下表

 UserName   UserId   
    -----      ----    
    Bob         445       
    Bob         450       
    Rachel      512       
    Rachel      520       
    Rachel      570       
    Simon       771       
    Simon       760 

我正在尝试对其进行旋转,以便为每个用户名创建一个新列, 每个用户名都列出了用户 ID

Bob       Rachel       Simon
445          512        771
450          520        760
             570

【问题讨论】:

    标签: sql sql-server tsql pivot


    【解决方案1】:

    以防万一您正在寻找动态支点

    示例

    Declare @SQL varchar(max) = '
    Select *
    From (
            Select * 
                  ,RN = row_number() over (partition by username order by UserId) 
            from #YourTable
         ) A
     Pivot (max(UserID) For [UserName] in (' + stuff((Select distinct ',' + QuoteName([UserName]) From  #YourTable Order By 1 For XML Path('')),1,1,'')  + ') ) p
    '
    
    --Print @SQL
    Exec(@SQL);
    

    退货

    RN  Bob   Rachel    Simon
    1   445   512       760
    2   450   520       771
    3   NULL  570       NULL
    

    【讨论】:

      【解决方案2】:

      这很棘手。您可以使用聚合,但需要对行进行编号:

      select max(case when username = 'Bob' then uid end) as bob,
             max(case when username = 'Rachel' then uid end) as Rachel,
             max(case when username = 'Simon' then uid end) as Simon      
      from (select t.*,
                   row_number() over (partition by username order by uid) as seqnum
            from t
           ) t
      group by seqnum
      order by seqnum;
      

      注意:这将按uid 对值进行排序,这与您的结果集略有不同。 SQL 表代表 无序 集合。原始行没有排序,除非列指定该排序。如果你有这样的列,你可以用它来代替order by uid 来代替row_number()

      【讨论】:

        猜你喜欢
        • 2012-04-19
        • 1970-01-01
        • 1970-01-01
        • 2017-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-18
        相关资源
        最近更新 更多