在数据透视查询中按ID对行进行分组

时间:2019-10-02 19:01:36

标签: sql sql-server pivot

我正在尝试创建数据透视查询以显示来自数据库的调查响应数据。

这是我到目前为止的查询:

declare
    @columns     nvarchar(max) ='',
    @sql         nvarchar(max) = '',
    @responseIDs nvarchar(max) = '';

select
    @columns+=QUOTENAME(QuestionLabel) + ','
from
    SurveyQuestions
where
    SurveyID=1
order by
    QuestionSort;

set @columns = LEFT(@columns, LEN(@columns)-1);
set @responseIDs = (select ResponseIDs from SurveyCart where SurveyCartID=7);

set @sql='
select * from ( 
    select 
        QuestionLabel, ResponseAnswer, ResponseID, AmountPaid = 
        (
            IIF(QuestionTypeID=2 and ResponseAnswer=''Yes'', QuestionValue, 0) +
            IIF(QuestionTypeID=6 and CAST(ResponseAnswer as int)>0, QuestionValue*Cast(ResponseAnswer as int), 0)
        )
    from 
        SurveyQuestions q
        inner join SurveyResponseAnswers ra 
            on q.QuestionID=ra.QuestionID
    where
        ResponseID in (' + @responseIDs + ')
) t
pivot(
    MAX(ResponseAnswer) for QuestionLabel in (' + @columns + ')
) as pivot_table;';

EXECUTE(@sql)

这是我得到的结果

ResponseID  AmountPaid  Attending?  Select     Cost with Quantities
19          0.00            NULL    Option 3   NULL
20          0.00            NULL    Option 1    
19          25.00           Yes     NULL       NULL
20          25.00           Yes     NULL       NULL
19          30.00           NULL    NULL       3

我想要的结果:

ResponseID  AmountPaid  Attending?  Select     Cost with Quantities
19          55.00           Yes     Option 3   3
20          25.00           Yes     Option 1    

我希望每个响应ID仅存在一行,并且“出勤”和“有成本的数量”中有空白点,我需要底部的结果以及要基于ResponseID加在一起的金额。

1 个答案:

答案 0 :(得分:0)

select 
    ResponseID,
    sum(case when QuestionLabel = 'AmountPaid' then
        iif(QuestionTypeID = 2 and ResponseAnswer = 'Yes', QuestionValue, 0) +
        iif(QuestionTypeID = 6 and cast(ResponseAnswer as int) > 0,
            QuestionValue * Cast(ResponseAnswer as int), 0)
    end) as "AmountPaid",
    min(case when QuestionLabel = 'Attending?'
        then ResponseAnswer end) as "Attending?",
    min(case when QuestionLabel = 'Select'
        then ResponseAnswer end) as "Select",
    min(case when QuestionLabel = 'Cost with quantities'
        then ResponseAnswer end) as "Cost with Quantities"
from 
    SurveyQuestions q
    inner join SurveyResponseAnswers ra 
        on q.QuestionID = ra.QuestionID
where ResponseID in (
    select ResponseIDs from SurveyCart where SurveyCartID = 7
);

我不完全了解“问题值”或“调查车”是什么,但我认为这应该很接近。除非您期望问题标签将来会改变,否则我不明白为什么您不能像这里已经使用大量ID值那样仅在此处对其进行硬编码。