Click here to Skip to main content
15,891,427 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
My Code as follows;
SQL
select * FROM Tb_SCh_TIme_Table P PIVOT (MAX(Faculty_Code) FOR Session IN ([1],[2],[3] ,[4])) AS PVT  where course = 'PH2' order by course,Date;

when i run the above query output as follows;
Date       Course   1    2   3   4
15/1/2013   PH2                  NR
15/1/2013   PH2                  CM

SQL
select course,  stuff((select ',' + cast(SubQry.Faculty_Code as varchar(50)) from Tb_SCh_TIme_Table As SubQry where SubQry.course = MainQry.course for XML Path('')), 1, 1,'') as Faculty_Code
from Tb_SCh_TIme_Table as MainQry where Course='PH2'
Group by MainQry.course.

when i run the above query output as follows;
Course   Faculty_Code
 PH2      NR,CM

using both query make into single sub query i want the final output to be as follows
 Date       Course   1    2   3    4
15/1/2013   PH2                   NR,CM

how can i do to get the final output as i mentioned above.please help me. i want the answer.
Posted
Updated 22-Jan-13 21:43pm
v2

Instead of using Tb_SCh_TIme_Table as your source for the pivot use your sub query so your source should have 1 record for each date,course and (1-4)

SQL
Date          Course         Num       Value
15/1/2013     PH2            1         NR,CM
15/1/2013     PH2            2         NR
15/1/2013     PH2            3         NR,CM,Oth



When you have that result pivot on the Num column.
 
Share this answer
 
According to me your following query is wrong.
SQL
select course,  stuff((select ',' + cast(SubQry.Faculty_Code as varchar(50)) from Tb_SCh_TIme_Table As SubQry where SubQry.course = MainQry.course for XML Path('')), 1, 1,'') as Faculty_Code
from Tb_SCh_TIme_Table as MainQry where Course='PH2'
Group by MainQry.course.

It should be corrected as follows
SQL
SELECT [Date],[Course],[Session],
    SUBSTRING((SELECT ','+ [Faculty_Code]
        FROM [Tb_SCh_TIme_Table ] dp2 
        WHERE dp2.[Date] = dp1.[Date] and dp2.[Course]=dp1.[Course] and dp2.[Session]=dp1.[Session]
    FOR XML PATH('')), 2, 8000) AS [Faculty_Code]
FROM [Tb_SCh_TIme_Table ] dp1
GROUP BY [Date],[Session],[Course]

Here is the complete query according to me
SQL
SELECT *
FROM (
SELECT [Date],[Course],[Session],
    SUBSTRING((SELECT ','+ [Faculty_Code]
        FROM [Tb_SCh_TIme_Table ] dp2 
        WHERE dp2.[Date] = dp1.[Date] and dp2.[Course]=dp1.[Course] and dp2.[Session]=dp1.[Session]
    FOR XML PATH('')), 2, 8000) AS [Faculty_Code]
FROM [Tb_SCh_TIme_Table ] dp1
GROUP BY [Date],[Session],[Course]
) P
PIVOT (
MAX([Faculty_Code])
FOR [Session] IN ([1],[2],[3] ,[4])
) AS PVT
WHERE [Course]='PH2'


Please check and get back to me if you need any more details.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900