Solved

I need help building Pivot tables and cross tab queries in SQL

Posted on 2011-03-21
5
226 Views
Last Modified: 2012-05-11
Hi Experts,
Is there a way to dynamically build cross tab queries and pivot tables in SQL?  If I build an application that will allow the user to select up to 3 fields, could this be done?

Thanks in advance,
mrotor
0
Comment
Question by:mainrotor
5 Comments
 
LVL 9

Expert Comment

by:mayank_joshi
ID: 35186846
0
 
LVL 16

Accepted Solution

by:
Imran Javed Zia earned 500 total points
ID: 35188311
Hi,
You can use one of followings:
select
ColID,
      max(Case When ColumnName='Col1' then  ColumnValue End) Col1,
      max(Case When ColumnName='Col2' then  ColumnValue End) Col2,
      max(Case When ColumnName='Col3' then  ColumnValue End) Col3
from tbl
Group by ColID

Or

SELECT *
FROM
(select ColumnName,ColumnValue,ColID from tbl
) as tab
PIVOT
 (
 max(ColumnValue)
 FOR ColumnName
 IN (ColID,ColumnName,ColumnValue)
 )
 AS p

Thanks
0
 
LVL 50

Expert Comment

by:Lowfatspread
ID: 35188593
you can go totally dynamic with dynamic sql....

or you could go partially dynamic if you have selection criteria that
allow for it...

what are you allowing the users to select ....

the pivoted columns (range)?
or the columns against which the data is to be displayed?

can you handle the naming of the columns on the returned result set?
0
 

Author Comment

by:mainrotor
ID: 35199094
Lowfatspread, I am allowing the users to select the columns.
0
 

Author Comment

by:mainrotor
ID: 35416951
Lowfatspread,
I am allowing the users to select the columns against which the data is to be displayed.
0

Featured Post

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how the fundamental information of how to create a table.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question