Solved

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

Posted on 2011-03-21
5
222 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

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Join & Write a Comment

In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
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.

706 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now