【问题标题】:SQL Transformation from rows to columns [duplicate]从行到列的SQL转换[重复]
【发布时间】:2015-01-18 13:24:52
【问题描述】:

我有一张桌子

ID VALUE BRAND
1 group1 Hollister
1 group2 Express
1 group 3 Persche 
2 Group1 Hollister
3 Group3 Persche

等等。并想转换成这样的东西,它在 sql 中的 ID 上是唯一的:

ID Hollister Express Persche 
1  Group1   Group2   Group3 
2  Group1   BLANK    Blank 
3  Blank    Blank    Group3

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    您可以使用pivot 或条件聚合来做到这一点:

    select id,
           max(case when brand = 'Hollister' then value end) as Hollister,
           max(case when brand = 'Express' then value end) as Express,
           max(case when brand = 'Persche' then value end) as Persche
    from table t
    group by id;
    

    这将产生NULL。如果你真的想要'':

    select id,
           max(case when brand = 'Hollister' then value else '' end) as Hollister,
           max(case when brand = 'Express' then value else '' end) as Express,
           max(case when brand = 'Persche' then value else '' end) as Persche
    from table t
    group by id;
    

    【讨论】:

      【解决方案2】:

      这是一个有效的PIVOT 选项:

      Select  * 
      From 
      (
          Select  value, Brand, id
          From    YourTable
      ) Source
      Pivot
      (
          Max(value)
          For Brand In ([Hollister],[Express],[Persche])
      ) P
      

      【讨论】:

        【解决方案3】:

        您可以使用 PIVOT 和 UNPIVOT 关系运算符将表值表达式更改为另一个表。

        这是一个例子:Convert Rows to columns using 'Pivot' in SQL Server

        select *
        from 
        (
          select store, week, xCount
          from yt
        ) src
        pivot
        (
          sum(xcount)
          for week in ([1], [2], [3])
        ) piv;
        

        【讨论】:

          猜你喜欢
          • 2014-09-08
          • 2017-01-30
          • 2015-07-01
          • 2020-02-23
          • 1970-01-01
          • 1970-01-01
          • 2011-03-22
          • 1970-01-01
          • 2016-11-29
          相关资源
          最近更新 更多