Select record from database in Pivot format in SQL Server

Last Reply one month ago By dharmendr

Posted one month ago

Hi team,

 Based on below data I am getting output as below.

EMPID, QuestionName, Answer can get pivot as below.

EMPID, Que1Name, Que2Name, Que3Name

1           Agree        DisAgree    Nutral

2           DisAgree    Agree         Nutral

CREATE TABLE #Question_Master([Que_ID] INT,[Que_Name] VARCHAR(100))
INSERT INTO #Question_Master VALUES(1,'How are u feeling today ?')
INSERT INTO #Question_Master VALUES(2,'Do you have good network connectivity at home?')
 
CREATE TABLE #Answer_Master([Ans_ID] INT,[Ans_Name] VARCHAR(50))
INSERT INTO #Answer_Master VALUES(1,'Agree')
INSERT INTO #Answer_Master VALUES(2,'Strongly Agree')
INSERT INTO #Answer_Master VALUES(3,'Disagree')
INSERT INTO #Answer_Master VALUES(4,'Nutral')
 
CREATE TABLE #Que_Ans_Trn_Master([EMP] INT,[Que_ID_FK] INT,[ANS_ID_FK] INT)
INSERT INTO #Que_Ans_Trn_Master VALUES(1,1,1)
INSERT INTO #Que_Ans_Trn_Master VALUES(1,2,4) 
 
SELECT QATM.EMP,QM.Que_Name [Question],AM.Ans_Name [Answer]
FROM #Que_Ans_Trn_Master QATM
INNER JOIN #Question_Master QM ON QATM.Que_ID_FK = QM.Que_ID
INNER JOIN #Answer_Master AM ON QATM.ANS_ID_FK = AM.Ans_ID

 

Posted one month ago

Refer below link and try at your end. Then report if any issue with query.

Execute dynamic pivot query with dynamic column in SQL Server