Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pivot data in T-SQL

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?

like image 374
JBone Avatar asked Aug 29 '11 15:08

JBone


People also ask

Is there a PIVOT function in SQL?

You can use the PIVOT and UNPIVOT relational operators to change a table-valued expression into another table. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output.

Can we use PIVOT in CTE?

This T-SQL script contains DDL to create a table and DML to insert a few rows of test data, then a CTE is provided which does some aggregations, while using the Pivot operator to show the data by year and month, along with a new yearly total amount also.

What are the limitations of the PIVOT operator in T SQL?

The design of the PIVOT and UNPIVOT operators sometimes leads to bugs and pitfalls in your code. The PIVOT operator's syntax doesn't let you explicitly indicate the grouping element. If you don't realize this, you can end up with undesired grouping elements.


1 Answers

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 )

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.

Other examples:

  • SQL Server PIVOT perhaps?
  • How do I build a summary by joining to a single table with SQL Server?
like image 75
Adriano Carneiro Avatar answered Sep 22 '22 21:09

Adriano Carneiro