繁体   English   中英

将 SQL 服务器中的行转换为列,方法是组合 2 列以形成新列

[英]Convert rows to columns in SQL Server by combining 2 columns to form the new column

我正在尝试完成与在 sql 服务器中有效地将行转换为列相关的事情,不同之处在于我有 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

任何帮助将不胜感激!

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

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;

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

数据

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;

Output

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM