结果集查询的链接 http://screencast.com/t/8Su2cACxBtq
我想将没有NULL值的数据显示为单行
with cte as (
Select QuestionID,SubmitDate,
Case when QuestionID=860 and Answers='Yes' then Answers End as 'Ans1A',
case when QuestionID=861 then Answers else NULL End as 'Answer2A',
case when QuestionID=862 then Answers ELSE NULL End as 'Answer3A',
case when QuestionID=863 then Answers Else NULL End as 'Answer4A',
Case when QuestionID=864 and Answers='Yes' then Answers End as 'Ans2B',
case when QuestionID=865 then Answers else NULL End as 'Answer2B',
case when QuestionID=866 then Answers ELSE NULL End as 'Answer3B',
case when QuestionID=867 then Answers Else NULL End as 'Answer4B'
From Question_Users Where SurveyId=28 and QuestionID in (860,861,862,863,864,865,866,867) and SubmitDate is not null
)
select *
from cte
以上sql查询的示例数据
QID + Ans1A + Ans2A+ Ans3A,Ans4A+ Ans1B+Ans2B+Ans3B+Ans4B
860 + Yes + Null + Null + Null + Null + Null + Null + Null
861 + Null + abc + Null + Null + Null + Null + Null + Null
862 + Null + Null + abc + Null + Null + Null + Null + Null
863 + Null + Null + Null + abc+ Null + Null + Null + Null
864 + Null + Null + Null + Null + abc+ Null + Null + Null
864 + Null + Null + Null + Null + Null + abc+ Null + Null
864 + Null + Null + Null + Null + Null + Null + abc+ Null
864 + Null + Null + Null + Null + Null + Null + Null + abc
860 + Yes + Null + Null + Null + Null + Null + Null + Null
861 + Null + abc + Null + Null + Null + Null + Null + Null
862 + Null + Null + abc + Null + Null + Null + Null + Null
863 + Null + Null + Null + abc+ Null + Null + Null + Null
864 + Null + Null + Null + Null + abc+ Null + Null + Null
864 + Null + Null + Null + Null + Null + abc+ Null + Null
864 + Null + Null + Null + Null + Null + Null + abc+ Null
864 + Null + Null + Null + Null + Null + Null + Null + abc
答案 0 :(得分:1)
我认为你可以使用聚合:
Select submitdate,
max(Case when QuestionID=860 and Answers='Yes' then Answers End) as Ans1A,
max(case when QuestionID=861 then Answers End) as Answer2A,
max(case when QuestionID=862 then Answers End) as Answer3A,
max(case when QuestionID=863 then Answers End) as Answer4A,
max(Case when QuestionID=864 and Answers='Yes' then Answers end) as Ans2B,
max(case when QuestionID=865 then Answers end) as Answer2B,
max(case when QuestionID=866 then Answers end) as Answer3B,
max(case when QuestionID=867 then Answers end) as Answer4B
From Question_Users
Where SurveyId = 28 and
QuestionID in (860, 861, 862, 863, 864, 865, 866, 867) and
SubmitDate is not null
Group by submitdate;