简体   繁体   中英

Pivot join with two columns having varchar datatype in SQL Server 2012

I need to use pivot to create time table from the following data:

在此处输入图片说明

I'm using this query

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 to

在此处输入图片说明

I used following SQL code to do that:

--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

Do help me out to get subjectname as value instead of subjectid

Since you are pivoting a VARCHAR, you can't use SUM , but have to use MAX or MIN

Try instead:

SET   @SQLQuery = 
    N'SELECT start_time,end_time, ' +   @PivotColumns + ' 
    FROM [dbo].[time_table]  
    PIVOT( MAX(subjectname) 
          FOR dd IN (' + @PivotColumns + ')) AS P'

Found answer for it which provides simpler way to get it. click to get answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM