Click here to Skip to main content
15,886,873 members
Articles / Database Development / SQL Server
Tip/Trick

Using Pivot In SQL for Reporting

Rate me:
Please Sign up or sign in to vote.
3.50/5 (3 votes)
28 Feb 2011CPOL 19.7K   8   3
Nice and fast way for reporting
Many times, we need to show some reports such as Department Wise Expense, or Subject wise marks of students where department and subject are stored in rows and we are to show all these as Columns. In all these situations, we can use SQL Pivoting.

For example, for Department Wise expense:

Suppose we store expenses as:

Dept ExDate       expense
_________________________
A   |  12 Jan |  10000
A   |  15 Jan |   9000
B   |  02 Feb |   8000
C   |  02 Feb |   8000
A   |  05 Feb |  10000
C   |  12 Feb |   8000


select ExDate, [A] as 'Store A Expense', [B] as 'Store B Expense', [C] as 'Store C Expense' from
(
select * from expenseTable
) ExpenseData
PIVOT
(
    sum(expense) for Dept in ([A],[B],[C]) 
)as FinalData


You can find one more detailed script here[^].

--Pankaj

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
• An Architect, developer, trainer, and student
• 10 years of experience in Architecture and Development of enterprise applications
• Extensive knowledge in designing and developing Web-based enterprise applications using open source and Microsoft Technologies
• Extensive experience in Angular, AngularJS, ReactJs, NodeJs, JavaScript, ASP.Net, C#, CSS, HTML

Comments and Discussions

 
GeneralMy vote of 5 Pin
pankajupadhyay298-Feb-13 7:47
professionalpankajupadhyay298-Feb-13 7:47 
GeneralReason for my vote of 3 It's a good attempt, nevertheless th... Pin
George Tryfonas11-Mar-11 2:33
George Tryfonas11-Mar-11 2:33 
Reason for my vote of 3
It's a good attempt, nevertheless this method is quite restricted given that you must know the columns for which you pivot in advance. It does not cover the general case where, in your particular example, stores may be added or removed.
GeneralReason for my vote of 3 Good attempt.... Pin
Pravin Patil, Mumbai28-Feb-11 3:12
Pravin Patil, Mumbai28-Feb-11 3:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.