在 T-SQL 中透视数据

2021-12-10 00:00:00 pivot sql tsql sql-server

我有一群人.让我们称他们为A,B,C.我有一张表格显示他们每个月的工资......

I have a group of people. Lets call them A,B,C. I have a table that shows how much they were paid each month....

PERSON|MONTH|PAID
A      JAN   10
A      FEB   20   
B      JAN   10   
B      FEB   20   
B      SEP   30   
C      JAN   10   
C      JUNE  20   
C      JULY  30   
C      SEP   40 

这张桌子可以而且确实会持续很多年..

THIS table can and does go on for years and years..

有没有办法对这个表进行透视(我认为没有什么需要聚合的,通常在透视中完成)在一个如下所示的表中?

Is there a way to pivot this table (nothing as I see really needs to be aggregated which is usually done in pivots) In a table that looks like the following?

     JAN    FEB    MAR    APR    MAY    JUN    JUL    AGU    SEP
A    10     20
B    10     20     -      -      -      -      -      -      30
C    10     -      -      -      -      20     30     -      40

以前没有遇到过这样的事情,但认为这是一个常见问题有什么想法吗?

Haven't run into something like this before but assume it is a common problem any ideas?

推荐答案

如果您使用的是 SQL Server 2005(或更高版本),这里是代码:

If you are using SQL Server 2005 (or above), here is the code:

DECLARE @cols VARCHAR(1000)
DECLARE @sqlquery VARCHAR(2000)

SELECT  @cols = STUFF(( SELECT distinct  ',' + QuoteName([Month])
                        FROM YourTable FOR XML PATH('') ), 1, 1, '') 


SET @sqlquery = 'SELECT * FROM
      (SELECT Person, Month, Paid
       FROM YourTable ) base
       PIVOT (Sum(Paid) FOR [Person]
       IN (' + @cols + ')) AS finalpivot'

EXECUTE ( @sqlquery )

无论您拥有多少不同的状态,这都将起作用.它使用 PIVOT 动态组合查询.对动态列执行 PIVOT 的唯一方法是动态组装查询,这可以在 SQL Server 中完成.

This will work no matter how many different status you have. It dynamically assembles a query with PIVOT. The only way you can do PIVOT with dynamic columns is by assembling the the query dynamically, which can be done in SQL Server.

其他示例:

  • 也许是 SQL Server PIVOT?
  • 如何通过将 SQL Server 连接到单个表来构建摘要?

相关文章