将不同的行分组到sql server的单行中
结果集查询的链接 我想在单行中显示没有空值的数据将不同的行分组到sql server的单行中,sql,tsql,Sql,Tsql,结果集查询的链接 我想在单行中显示没有空值的数据 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 Questio
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
我认为您可以使用聚合:
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;
请编辑您的问题并提供示例数据和所需结果。您尝试过的任何查询都很有用。我也使用了pivot表,但它只返回一行,我尝试在上面的查询中返回一行。您的示例数据表明您只需要一行。也许您希望通过
.submitdate
进行聚合。