MS-SQL2008を使用しています。「Y」またはNull値を持つ場所に基づいて異なる列を持つテーブルがあります。この表には、調査結果からの場所以外のデータも含まれています。1つまたはすべてに基づいて場所を保持するように誘惑可能な@TempLocationを設定しました。日付範囲内の1つ以上の場所の行からの「Y」に基づいてテーブルから行を選択する必要があります。
TableID Northwest Northeast Southwest Southeast Batchno first_choice date_completed
1 Y Y Y 1 A 2012-11-10
2 Y Y 1 SA 2012-19-10
3 Y Y 1 N 2012-07-10
4 Y Y Y 2 A 2012-10-10
5 Y 2 A 2012-16-10
6 Y Y 2 D 2012-21-10
7 Y NULL A 2012-19-10
8 Y Y Y Y 3 SA 2012-11-10
9 Y 3 A 2012-10-10
10 Y Y 3 A 2012-07-10
1つの場所を正常にプルするための動的SQLステートメントを作成しましたが、すべてをプルすることは可能ですか?
select ''' + (SELECT * FROM @TempLocation) + ''',
count(batchno),
count(case when first_choice is not null then batchno end),
count(case when t.First_choice =''SD'' then 1 end) ,
count(case when t.First_choice=''D'' then 1 end) ,
count(case when t.First_choice=''N'' then 1 end) ,
count(case when t.First_choice=''A'' then 1 end) ,
count(case when t.First_choice=''SA'' then 1 end)
from customer_satisfaction_survey t
where t.date_completed>= ''' + CAST(@beg_date AS VARCHAR) + '''
and t.date_completed < ''' + CAST(dateadd(day,1,@end_date) AS Varchar) + '''
and t.' + (SELECT * FROM @TempLocation) + ' = ''Y'''
Allの結果は次のようになります。
Number Location Total Total2 SA A N D SD
1 Northwest 6 6 1 3 1 1 0
2 Northeast 5 4 2 2 1 0 0
3 Southwest 4 4 1 3 0 0 0
4 Southeast 6 6 2 3 0 1 0