Sql 在透视查询中按ID对行进行分组
我正在尝试创建一个pivot查询来显示数据库中的调查响应数据 以下是我目前的疑问:Sql 在透视查询中按ID对行进行分组,sql,sql-server,pivot,Sql,Sql Server,Pivot,我正在尝试创建一个pivot查询来显示数据库中的调查响应数据 以下是我目前的疑问: declare @columns nvarchar(max) ='', @sql nvarchar(max) = '', @responseIDs nvarchar(max) = ''; select @columns+=QUOTENAME(QuestionLabel) + ',' from SurveyQuestions where Su
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只有一行,并且在出席和数量成本中有空白点,我需要底部行的结果和基于响应ID加在一起的金额
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值进行了硬编码。这将有助于实际数据插入测试,以及您想要的实际输出。但是根据您目前的描述,您可能必须使用GROUP BY ResponseID并对金额进行求和,在其他列中使用MIN/MAX。我认为您只需去掉pivot并使用一个简单的
GROUP BY
。您已经在硬编码QuestionTypeId
值。是否确实需要使ResponseID
动态化。不管是哪种方式,只要用case
或if
将列表达式包装起来,就像你已经做过的那样。我需要透视图,因为我正在用问题标签创建列,这些问题标签位于与响应不同的表中。问题标签将不同,因为用户可以使用任何工具进行自己的调查和表单问题。这就是为什么它必须是动态的。