【发布时间】:2019-10-02 19:01:36
【问题描述】:
我正在尝试创建一个透视查询来显示数据库中的调查响应数据。
这是我目前的查询:
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 只有一行,并且在 Attinging 和 Cost With quantity 中有空白点我需要底部行的结果和要根据 ResponseID 相加的金额。
【问题讨论】:
-
这将有助于实际数据插入以进行测试,以及您想要的实际输出。但鉴于您到目前为止的描述,您可能必须使用 GROUP BY ResponseID 并对金额求和,其他列上使用 MIN/MAX。
-
我认为您只需摆脱枢轴并使用简单的
group by。您已经对QuestionTypeId值进行了硬编码,是否真的需要使ResponseIDs 动态化。无论哪种方式,只需使用case或if包装列表达式,就像您已经做过的那样。 -
我需要数据透视表,因为我正在从 QuestionLabels 中创建列,这些列与 Responses 位于不同的表中
标签: sql sql-server pivot