SQL Server Dynami c Pivoting - Не используется Pivot с счетчиком - PullRequest
0 голосов
/ 04 мая 2020

Мне нужно сводить вопросы с их ответами. Желаемый результат сводного запроса приведен ниже, а также структура таблицы. enter image description here enter image description here enter image description here enter image description hereenter image description here

Я создал SQL скрипку Здесь Sql Скрипка . Я видел много примеров count с pivot, но не смог найти что-то похожее на это.

Ответы [ 2 ]

1 голос
/ 04 мая 2020

Вам просто нужно несколько объединений для получения базовых данных и динамический c pivot для отображения результата в нужном формате.

попробуйте следующее:

drop table if exists #temp

--base table with all details
select s.ID SurveyID, s.SubmittedBy, sq.Question, sa.Answer
into #temp
from @Survey s
join @SurveyMaster sm on sm.ID = s.SurveyMasterID
join @SurveyQuestion sq on sq.SurveyMasterID = s.SurveyMasterID
join @SurveyAnswers sa on sa.SurveyQuestionID = sq.ID and sa.SurveyID = s.ID

--dynamic pivot
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Question) 
            FROM #temp c
            ORDER BY 1 DESC
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT SurveyID, SubmittedBy, ' + @cols + ' from 
            (
                select SurveyID, SubmittedBy, Question, Answer
                from #temp
            ) x
            pivot 
            (
                max(Answer)
                for Question in (' + @cols + ')
            ) p '

--execution
execute(@query)

Пожалуйста, найдите дб <> скрипка здесь .

1 голос
/ 04 мая 2020
declare @sqlstring as varchar(max) = '';
SELECT
   @sqlstring = STUFF((
   SELECT distinct
      ',' + '[' + isnull(sq.Question, '''') + ']' 
   from
      @surveyanswers sa 
      join
         @SurveyQuestion sq 
         on sq.ID = sa.SurveyQuestionID 
      join
         @survey sv 
         on sv.SurveyMasterID = sq.SurveyMasterID FOR XML PATH('')), 1, 1, '')          
         select
            sa.SurveyID,
            sv.SubmittedBy,
            sq.Question,
            sa.Answer into ##temp 
         from
            @surveyanswers sa 
            join
               @SurveyQuestion sq 
               on sq.ID = sa.SurveyQuestionID 
            join
               @survey sv 
               on sv.SurveyMasterID = sq.SurveyMasterID 
         set
            @sqlstring = 'SELECT  SurveyID,SubmittedBy,' + @sqlstring + '  FROM   (select * from  ##temp ) t ' + ' PIVOT ( ' + ' max(Answer)  FOR Question IN (' + @sqlstring + ' ) ) AS pivot_table' execute(@sqlstring);

РЕЗУЛЬТАТ: enter image description here

...