简体   繁体   English

使用日期列将表格从长变宽

[英]Reshape table long to wide using date column

I'm trying to reshape my table long to wide using the data column in the table.我正在尝试使用表中的数据列将我的表从长到宽重塑。 The data looks like this:数据如下所示:

ID    Revenue      Year
456    78645       2015
456    52134       2016
456    95431       2017
735    65423       2015
735    25357       2016
735    65732       2017

I'm trying to reshape the table long to wide like this:我正在尝试像这样将桌子从长到宽重塑:

ID      2015      2016     2017
456    78645     52134     95431
735    65423     25357     65732 

Is there a way to do it in SQL Server?有没有办法在 SQL 服务器中做到这一点? Thanks.谢谢。

You can do it by creating and executing dynamic sql query.您可以通过创建和执行动态 sql 查询来做到这一点。

Query询问

declare @query as varchar(max);
set @query = 'select [id], ';
select @query += stuff((
        select distinct ',sum(case [year] when '+ 
        cast([year] as varchar(4)) +
        ' then [revenue] end) as [' + cast([year] as varchar(4)) + ']'
        from [table_name]
        for xml path('')
    ),
    1,1, ''
);
set @query += ' from [table_name] group by [id];';

exec(@query);

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

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