Click here to Skip to main content
16,020,347 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I need to use pivot to create time table from the following data:
and records contain inner join.I have tried and provided code but not able to get it
I hope it is sufficient data

starttime endtime subjname dd
9            11    History Monday
11           13    Physics Tuesday


I'm using this query to generate above columns
SQL
select 
    start_time, end_time, s.subj_name, tt.dd
from 
    time_table tt 
inner join 
    subj s on tt.subjid = s.subjid 


I am able to pivot my result using below code

SQL
--Declare necessary variables
DECLARE   @SQLQuery AS NVARCHAR(MAX)
DECLARE   @PivotColumns AS NVARCHAR(MAX)

--Get unique values of pivot column  
SELECT @PivotColumns = COALESCE(@PivotColumns + ',','') + QUOTENAME(dd)
FROM (SELECT DISTINCT(dd)
      FROM time_table tt
      WHERE divid = 1 AND tt.active = 1) AS PivotExample

SELECT @PivotColumns

--Create the dynamic query with all the values for 
--pivot column at runtime
SET   @SQLQuery = 
    N'SELECT start_time,end_time, ' +   @PivotColumns + ' 
    FROM [dbo].[time_table]  
    PIVOT( SUM(subjid) 
          FOR dd IN (' + @PivotColumns + ')) AS P' 

SELECT   @SQLQuery

--Execute dynamic query
EXEC sp_executesql @SQLQuery


And getting output as
Starttime endtime Monday Tuesday Wednesday
9          11     7        8       null
11         13     null     7         9



Here i am getting subjectid and but I want Subject Name which is in different as shown in above query,Help me out with this issue.I have tried to give max() agreegate function since it is an varchar but i guess getting error due to join
Thank you.
Posted
Updated 19-Jun-16 23:39pm
v2
Comments
RedDk 18-Jun-16 12:26pm    
The word "PIVOT" is really a nasty database user's word for the more pleasant word, used by mathematicians (linear algebra) and the like, "TRANSPOSE". Look up transpose usg Google with "MS SQL" and "How to". The place to start ... experimenting.

1 solution

If you use the form of the PIVOT query that looks like
SQL
SELECT * FROM 
(
    -- source query
) src
PIVOT
(
    -- pivot definition
)
rather than the format you are using then you can easily add the join
--Create the dynamic query with all the values for 
--pivot column at runtime
SET   @SQLQuery = 
    N'SELECT * FROM
	(SELECT start_time,end_time,subj_name,dd
    FROM [dbo].[time_table] tt 
	INNER JOIN subj s on tt.subjid = s.subjid 
	) SRC
    PIVOT( MAX(subj_name) 
          FOR dd IN (' + @PivotColumns + ')) AS P' 
Notice I'm using MAX() rather than SUM() to get the course name
 
Share this answer
 
Comments
Member 10202727 20-Jun-16 13:37pm    
Thanx buddy ....
You rocks......

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