【问题标题】:sql pivot function for a table with only 2 columns只有 2 列的表的 sql 数据透视函数
【发布时间】:2014-03-25 04:43:43
【问题描述】:

我正在尝试使用 SQL Server 中的数据透视函数来转换一些结果,但遇到了麻烦。

该表只有 2 列,如下所示:

company      category
-----        -----
company 1    Arcade 
company 1    Action 
company 2    Arcade 
company 2    Adventure

我想把它改成这样:

company      category 1     category 2
-----        -----          -----
company 1    Arcade         Action    
company 2    Arcade         Adventure

到目前为止,我能找到的只是枢轴函数的示例,其中原始结果中的第 3 列带有“类别 1”或“类别 2”,然后使用这些列中的值作为新的名称,旋转的列。

我想做的只是从头开始定义列的名称。有没有办法用枢轴功能做到这一点?

提前致谢!

【问题讨论】:

    标签: sql-server pivot


    【解决方案1】:

    由于您需要包含category1category2 等的第三列,因此我建议您先将row_number() 之类的窗口函数应用于您的数据,然后再尝试将数据转换为列。 row_number() 函数将为每个 companycategory 创建一个唯一的序列号,然后您将使用此计算值来透视数据。

    转换数据的最简单方法是使用聚合函数和 CASE 表达式。首先,您将使用子查询生成row_number()

    select company,
      max(case when seq = 1 then category end) Category1,
      max(case when seq = 2 then category end) Category2
    from
    (
      select company, category,
        row_number() over(partition by company
                                  order by company) seq
      from yourtable
    ) d
    group by company;
    

    SQL Fiddle with Demo

    现在,如果您想使用 PIVOT 函数,您仍然可以使用 row_number(),但您可以将新的计算序列作为新的列名:

    select company, category1, category2
    from
    (
      select company, category,
        'category'+
          cast(row_number() over(partition by company
                                  order by company) as varchar(10)) seq
      from yourtable
    ) d
    pivot
    (
      max(category)
      for seq in (Category1, Category2)
    ) piv;
    

    SQL Fiddle with Demo。这些会产生以下结果:

    |   COMPANY | CATEGORY1 | CATEGORY2 |
    |-----------|-----------|-----------|
    | company 1 |    Arcade |    Action |
    | company 2 |    Arcade | Adventure |
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      相关资源
      最近更新 更多