SQL动态数据透视查询

时间:2015-10-16 18:32:50

标签: sql sql-server pivot

如果可能,我需要一个数据透视表的帮助。不确定它是否可以完成。以下是我的例子。 的问题

KeyEvent

答案

enter image description here

用户回答

enter image description here

回答Pivot

enter image description here

感谢您的帮助。

enter image description here

我附上了数据库结果的屏幕截图,其中有数据透视工作。下面的代码按照它应该转动,并且工作正常。如果您可以查看“Subject has exp ...”列,我希望该列重复三次,标题是问题,但我也希望每个可能的答案都与问题一起显示。

再次感谢!

再次Thansk。

以下是代码示例:

DECLARE @columns VARCHAR(MAX)

SELECT  @columns = COALESCE(@columns + ','+QUOTENAME([QuestionText]),QUOTENAME([QuestionText]))

FROM         SchemaWema.vts_vwSurvey INNER JOIN

                      Question ON SchemaWema.vts_vwSurvey.SurveyID = SchemaWema.vts_vwQuestion.SurveyID
WHERE SchemaWema.vts_vwSurvey.DecisionSetId = 598 AND SchemaWema.vts_vwSurvey.FormType = 1

Set @columns =  REPLACE(@columns, '[]', '[No Name Given]')

DECLARE @sql NVARCHAR(MAX)=N' SELECT  * FROM
(

        SELECT     Project.PROJECTNAME, Project.ID, 
                        Sites.PROJECTSTUDYSITENUMBER,  Sites.PROJECTSTUDYSITENAME,
                        Study.PROJECTSTUDYNAME, Study.PROJECTSTUDYNUMBER,
                        Survey.SurveyID,     Question.QuestionID,  Cases.SITEID, Cases.EVENTDATE, 
                              Cases.SUBJNO, Cases.EventType, Cases.TriggerEvent, 
                              Cases.DecisionSetID, Cases.PanelID, Cases.RECORDSTATUS, 
                              Project.PROJECTSPONSOR,  VoterAnswers.AnswerID, VoterAnswers.VoterID,
                              VoterAnswers.AnswerText AS FreeTypedAnswers, Voter.VoteDate, Users.SHOWNNAME, Panel.PANELNAME,  Sites.COUNTRY,
                              Cases.VERSIONID, cases.CSID, cases.CASENUMBER,Cases.CASEDATEUPDATED AS LASTUPDATED,
                              Cases.DECISIONSETNAME,
                              Question.QuestionText,
                        CASE 
                            WHEN
                                CAST(VoterAnswers.AnswerText AS VARCHAR(MAX)) IS NULL OR CAST(VoterAnswers.AnswerText AS VARCHAR(MAX)) = ''''
                            THEN
                                Answer.AnswerText
                        ELSE
                            CAST(Answer.AnswerText AS VARCHAR(MAX)) 

                    END AS AnswerText
          FROM
        (
                SELECT     a.ID, a.STUDYID, a.SITEID, a.CSID, a.VERSIONID, a.CASENUMBER, a.CASEINITIALS, a.EVENTDATE, a.CASEDETAILSFILE, a.CASEDETAILSFILEVERSION, 
                                      a.CASESTATUS, a.RECORDSTATUS, a.CASEDATEUPDATED, a.PROJECTDATEUPDATED, a.PanelID, a.DecisionSetID, a.SUBJNO, a.EventType, a.TriggerEvent, 
                                      a.Priority, a.id1, a.id2, a.dateid, a.dateiddt1, a.dateiddt2, a.extratext1, a.extratext2, SchemaWema.PROJECTPANELDECISIONSETVIEW.DECISIONSETNAME
                FROM         SchemaWema.PROJECTCASE AS a LEFT OUTER JOIN
                                      SchemaWema.PROJECTPANELDECISIONSETVIEW ON a.DecisionSetID = SchemaWema.PROJECTPANELDECISIONSETVIEW.DECISIONSETID
                WHERE     (a.CASEDATEUPDATED =
                                          (SELECT     MAX(CASEDATEUPDATED) AS Expr1
                                            FROM          SchemaWema.PROJECTCASE AS b
                                            WHERE      (a.ID = PROJECTID) AND (a.CSID = CASEID) AND (a.VERSIONID = VERSIONID) )) AND (a.RECORDSTATUS <> ''D'')
        )Cases
        LEFT OUTER JOIN
        (
                SELECT     PROJECTID, PROJECTNAME,  PROJECTSPONSOR
                FROM         SchemaWema.PROJECT AS a
                WHERE     (PROJECTDATEUPDATED =
                                  (SELECT     MAX(PROJECTDATEUPDATED) AS Expr1
                                    FROM          SchemaWema.PROJECT AS b
                                    WHERE      (a.ID = PROJECTID))) AND (RECORDSTATUS <> ''D'')

        ) Project on
        Project.ID = Cases.ID
        LEFT OUTER JOIN
        (
                SELECT  DISTINCT  a.ID, a.STUDYID, a.SITEID, a.PROJECTSTUDYSITENAME, a.PROJECTSTUDYSITENUMBER, SchemaWema.PROJECTSTUDYVIEW.PROJECTSTUDYNAME, a.COUNTRY
                FROM         SchemaWema.PROJECTSTUDYSITE AS a INNER JOIN
                                      SchemaWema.PROJECTVIEW ON a.ID = SchemaWema.PROJECTVIEW.ID INNER JOIN
                                      SchemaWema.PROJECTSTUDYVIEW ON a.ID = SchemaWema.PROJECTSTUDYVIEW.ID AND 
                                      a.STUDYID = SchemaWema.PROJECTSTUDYVIEW.STUDYID
                WHERE     (a.PROJECTSTUDYSITEDATEUPDATED =
                                          (SELECT    MAX(PROJECTSTUDYSITEDATEUPDATED) AS Expr1
                                            FROM          SchemaWema.PROJECTSTUDYSITE AS b
                                            WHERE      (a.ID = PROJECTID) AND (a.STUDYID = STUDYID) AND (a.SITEID = SITEID))) AND (a.RECORDSTATUS <> ''D'')

        )Sites on
        Cases.SITEID = Sites.SITEID 
        LEFT OUTER JOIN
        (
                SELECT  DISTINCT   PROJECTID, STUDYID, PROJECTSTUDYNAME, PROJECTSTUDYNUMBER, PROJECTSTUDYDESCRIPTION
                FROM         SchemaWema.PROJECTSTUDY AS a
                WHERE     (PROJECTSTUDYDATEUPDATED =
                                          (SELECT     MAX(PROJECTSTUDYDATEUPDATED) AS Expr1
                                            FROM          SchemaWema.PROJECTSTUDY AS b
                                            WHERE      (a.ID = PROJECTID) AND (ISNULL(a.STUDYID, ''0'') = ISNULL(STUDYID, ''0'')))) AND (RECORDSTATUS <> ''D'')
        )Study on
        Study.STUDYID = Cases.STUDYID

         inner join
         (
                SELECT     VoterID, UID, SurveyID, ContextUserName, VoteDate, StartDate, IPSource, Validated, ResumeUID, ResumeAtPageNumber, ProgressSaveDate, 
                            ResumeQuestionNumber, ResumeHighestPageNumber, LanguageCode, SurveyStatus, VoteAcceptRejectDate, CaseID, VersionID, PdfFileName, voterSurveyStatus, 
                            dateupdated, recordstatus, modifiedby, changereason
                FROM         SchemaWema.vts_tbVoter AS a
                WHERE     (dateupdated =
                                          (SELECT     MAX(dateupdated) AS Expr1
                                            FROM          SchemaWema.vts_tbVoter AS b
                                            WHERE      (a.VoterID = VoterID) AND (a.SurveyID = SurveyID) AND (a.CSID = CaseID) AND (a.VersionID = VersionID)))

         ) Voter on

         Voter.CSID = Cases.CSID
        AND Voter.VersionID = Cases.VersionID
        Inner Join
          (
                    SELECT  DISTINCT   SurveyID, DecisionSetId, FormType 

                        FROM         SchemaWema.vts_tbSurvey AS a
                        WHERE     (dateupdated =
                                  (SELECT     MAX(dateupdated) AS Expr1
                                    FROM          SchemaWema.vts_tbSurvey AS b
                                    WHERE      (a.SurveyID = SurveyID))) AND (recordstatus <> ''D'')
        ) Survey on
         Survey.SurveyID = Voter.SurveyID 
        inner Join
        (
                SELECT  DISTINCT
                                      VoterID, AnswerID, SectionNumber, CAST(AnswerText AS varchar(MAX)) AnswerText, SurveyID, CaseID, versionID
                FROM         SchemaWema.vts_tbVoterAnswers AS a
                WHERE     (dateupdated =
                                  (SELECT  MAX(dateupdated) AS Expr1
                                    FROM          SchemaWema.vts_tbVoterAnswers AS b
                                    WHERE      (a.VoterID = VoterID) AND (a.AnswerID = AnswerID) AND (a.SectionNumber = SectionNumber) AND (a.SurveyID = SurveyID) AND (a.CSID = CaseID) AND 
                                                           (a.versionID = versionID))) AND (recordstatus <> ''D'')
        )VoterAnswers on
        VoterAnswers.SurveyID = Survey.SurveyID
        AND VoterAnswers.CSID = Voter.CSID
        AND Voter.VoterID = VoterAnswers.VoterID
        AND VoterAnswers.versionID = Voter.versionID
        AND VoterAnswers.SurveyID = Voter.SurveyID
        FULL OUTER JOIN
        (

                select  DISTINCT a.USERID, a.USERNAME, a.FIRSTNAME, a.LASTNAME, a.SHOWNNAME
                from SchemaWema.users as a
                WHERE (a.userdateupdated =
                     (SELECT     MAX(b.userdateupdated) AS Expr1
                     FROM          SchemaWema.users AS b
                     WHERE   (a.userID = b.userID)  )) 
                 AND (a.RECORDSTATUS <> ''D'')
        ) Users on
        VoterAnswers.VoterID = Users.USERID
        AND Voter.VoterID = Users.USERID
        inner join
        (
                SELECT   DISTINCT  AnswerID, QuestionID,  AnswerText FROM         SchemaWema.vts_tbAnswer AS a
                            WHERE     (dateupdated =
                                (SELECT     MAX(dateupdated) AS Expr1
                                FROM          SchemaWema.vts_tbAnswer AS b
                                WHERE      (a.AnswerID = AnswerID))) AND (recordstatus <> ''D'')
        ) Answer  on
          Answer.AnswerID = VoterAnswers.AnswerID 
          inner Join
          (
                    SELECT   DISTINCT  QuestionID,SurveyID,  QuestionText
                        FROM         SchemaWema.vts_tbQuestion AS a
                        WHERE     (dateupdated =
                                  (SELECT     MAX(dateupdated) AS Expr1
                                    FROM          SchemaWema.vts_tbQuestion AS b
                                    WHERE      (a.QuestionID = QuestionID))) AND (recordstatus <> ''D'')
        ) Question on
          Answer.QuestionID = Question.QuestionID
          AND Question.SurveyID = Survey.SurveyID
          AND Question.SurveyID = VoterAnswers.SurveyID
        inner join
        (
                SELECT DIStinct
                      [PANELID]  ,[PANELNAME]
                  FROM [AdjudicateV3].[Adjudicate].[PROJECTPANELVIEW]
        )Panel on
        Panel.PANELID = Cases.PanelID

        WHERE  CASEs.ID = ' + @ID + ' AND Survey.DecisionSetId = '+ DeeSetId +' AND Survey.FormType = '+ @Forms +'

) AS SourceTable
PIVOT
(
        MAX(AnswerText)
        FOR QuestionText IN ('+@columns+')
) AS PivotTable'

1 个答案:

答案 0 :(得分:1)

可以使用动态轴来完成。

你要做的第一件事是建立你将用于枢轴的cols ..

declare @cols varchar(max)
select @cols = Coalesce(@cols + ', ', '') + '[' + q.Question + '(' + a.Question + ')]'
from Questions q
join Answers a on q.ID = a.QuestionID

这会将您想要的所有列标题连接成一个字符串,如

[What is your favorite Car Color(Blue)], [What is your favorite Car Color(Red)]

将列名放在括号内非常重要...

下一步是构建您的透视查询

declare @sql varchar(max)
set @sql = 'Select [User], ' + @cols + ' from (
            select ua.[User], ''X'' as Chosen, 
                q.Question + ''('' + a.Question + '')'' Answer
            from UserAnswers ua
            join Answers a On ua.AnswerId = a.ID and ua.QuestionID = a.QuestionID
            join Questions q on a.QuestionID = q.ID 
            ) t
            pivot (
               max(Chosen)
               for Answer IN (' + @cols + ')
            ) p'
exec(@sql)

这将创建一个子查询,其中有三列User,Chose,Answer ..用户是用户名,每个记录选择的只是一个X,而答案是用于转动的。答案看起来像上面的列名称没有括号..

接下来它会转动子查询..并选择名称和动态列..

SQL Fiddle Example