【问题标题】:Convert rows to columns in SQL Server by combining 2 columns to form the new column通过组合 2 列形成新列,将 SQL Server 中的行转换为列
【发布时间】:2020-10-09 13:56:40
【问题描述】:

我正在尝试完成与Efficiently convert rows to columns in sql server 相关的事情 不同之处在于我有 2 列需要形成新列。

所以我使用了前面提到的 SO 帖子中的这个例子,因为我有 1-N 列:https://data.stackexchange.com/stackoverflow/query/497433

这是我目前所拥有的:https://data.stackexchange.com/stackoverflow/query/1307538

我只是无法弄清楚如何在第二个(已注释)查询中组合年份/季度。

最后我想:

Cols: 2022Q1  2022Q2  2022Q3  2022Q4  2022Q1
Vals: 123     456     345     234     789

任何帮助将不胜感激!

【问题讨论】:

  • 您使用的是什么版本的 SQL Server?
  • 我必须支持 2018 和 Azure SQL

标签: sql sql-server pivot dynamic-pivot


【解决方案1】:

您需要在透视之前计算子查询中的年/季度字符串。我认为你想要的逻辑是:

set @query = 
    n'select ' + @cols + n' from 
    (
        select [count], 
            convert(nvarchar, [year]) + ''q'' + convert(nvarchar, [quarter]) yyyyqq
        from #yourtable
    ) x pivot (
        max([count])
        for yyyyqq in (' + @cols + n')
    ) p';

exec sp_executesql @query;

【讨论】:

    【解决方案2】:

    如果您使用的是最新版本的 SQL Server,您可以使用 CONCAT 和 STRING_AGG 函数来组合查询字符串,然后动态执行。数据来自您的链接。

    数据

    drop table if exists #yourtable;
    go
    create table #yourtable
        ([Id] int, [Year] int, [Quarter] int, [Count] int);
        
    insert into #yourtable([Id], [Year], [Quarter], [Count]) values
        (1, 2022, 1, 123),
        (2, 2022, 2, 456),
        (3, 2022, 3, 345),
        (4, 2022, 4, 234),
        (5, 2023, 1, 789);
    

    查询

    declare
      @select         nvarchar(max)=N'select',
      @str1           nvarchar(max)=N' sum(case when [Year]=',
      @str2           nvarchar(max)=N' and [Quarter]=',
      @str3           nvarchar(max)=N' then [Count] else 0 end) as [',
      @str4           nvarchar(max)=N']',
      @from           nvarchar(max)=N' from #yourtable;',
      @sql            nvarchar(max);
    
    select @sql=concat(@select,
                       string_agg(concat(@str1, [Year], @str2, [Quarter], @str3, 
                                         [Year], N'Q',[Quarter], @str4), N','),
                       @from)
    from #yourtable
    
    exec sp_executesql @sql;
    

    输出

    2022Q1  2022Q2  2022Q3  2022Q4  2023Q1
    123     456     345     234     789
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 2010-10-22
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多