Home All Groups Group Topic Archive Search About

A pivot table/Report with dynamic columns??

Author
15 Sep 2006 4:06 PM
MittyKom
Hi All

I am trying to make a pivot table with dynamic columns. I have included
below all the queries i am using. How do I change the query so that the
columns for Tr1, Amt1, [Description1], Duedate1, Tr2, Amt2, [Description2],
Duedate2 etc. will display based on what is available instead of hardcoding.

-->>This is the table structure with all the data.
Create table TempTb ( Trn int, F_id varchar(20), [Amount] decimal(18,2),
[Description] char(60), Duedate smalldatetime )

-->> This will give the results i want but i have to hardcode the columns 
which i would like to avoid.

SELECT F_name, F_id
--1st Tr1
,Tr1 =               ISNULL((SELECT distinct trn FROM TempTb WHERE Trn = 1 AND
F_id = O.F_id),0)
,Amt1 =       ISNULL((SELECT distinct Amount FROM TempTb WHERE Trn = 1 AND F_id
= O.F_id),0)
,[Description1] = ISNULL((SELECT distinct [Description] FROM TempTb WHERE
Trn = 1 AND F_id = O.F_id),0)
--2nd Tr2
,Tr2 =               ISNULL((SELECT distinct trn FROM TempTb WHERE Trn = 2 AND
F_id = O.F_id),0)
,Amt2 =       ISNULL((SELECT distinct Amount FROM TempTb WHERE Trn = 2 AND F_id
= O.F_id),0)
,[Description2] = ISNULL((SELECT distinct [Description] FROM TempTb WHERE
Trn = 2 AND F_id = O.F_id),0)
--3rd Tr3
,Tr3 =             ISNULL((SELECT distinct trn FROM TempTb WHERE Trn = 3 AND F_id
= O.F_id),0)
,Amt3 =       ISNULL((SELECT distinct Amount FROM TempTb WHERE Trn = 3 AND F_id
= O.F_id),0)
,[Description3] = ISNULL((SELECT distinct [Description] FROM TempTb WHERE
Trn = 3 AND F_id = O.F_id),0)
FROM TempTb O
GROUP BY F_name, F_id

Is this possible? I have looked at some other solutions but they do not suit
my problem as i am using DISTINCT. Thank you in advance.

AddThis Social Bookmark Button