2016-05-07 20 views
1
http://screencast.com/t/8Su2cACxBtq

、SQL Serverの単一の行に異なる行をグループ化

は私が単列にNULL値のないデータを表示したい結果セットのクエリの

リンク、上記のSQLクエリの

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 

サンプル・データ

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; 
+0

私はピボットテーブルも使用しましたが、1つの行だけを返します。 –

+0

サンプルデータは、1行だけを必要とすることを示唆しています。おそらく、 '.submitdate'で集計したいと思うかもしれません。 –

関連する問題