Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2011-03-21
5
Medium Priority
?
235 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 2000 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
This month, Experts Exchange sat down with resident SQL expert, Jim Horn, for an in-depth look into the makings of a successful career in SQL.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how the fundamental information of how to create a table.

824 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