我正在使用MS-SQL2008。我有一个表,根据它的位置有不同的列,它将有一个'Y‘或Null值。该表还包含来自调查结果的位置以外的其他数据。我已经设置了一个temptable @TempLocation来保存基于one或all的位置。我需要根据'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 我已经创建了一个动态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'''所有结果将如下所示。
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发布于 2012-12-19 04:33:47
我不得不认为您正在以错误的方式处理这个问题,因为您的数据没有标准化。您应该做的第一件事是使用UNPIVOT对数据进行规范化。我假设您使用的是SQL Server,因为您的语法说明了这一点。不过,用数据库标记所有问题是个好主意。
您可以使用如下语句取消透视数据:
select BatchNo, FirstChoice, DateCompleted, Location
from d
unpivot (val for location in (Northwest, Northeast, Southwest, Southeast)) as unpvt接下来,设置临时表,使每个位置都有单独的行。然后,您可以在没有动态SQL的情况下进行连接。类似于:
with dnorm as (
THE NORMALIZATION QUERY HERE
)
select dnorm.location, count(*) as total,
sum(case when dnorm.first_choice is not null then 1 else 0 end) as total2,
sum(case when dnorm.first_choice = 'SA' then 1 else 0 end) as SA,
. . .
from dnorm join
@TempLocation tl
on dnorm.location = tl.location
where ALL YOUR WHERE CONDITIONS HERE最后的查询类似于:
with dnorm as (
select BatchNo, FirstChoice, DateCompleted, Location
from d
unpivot (val for location in (Northwest, Northeast, Southwest, Southeast)) as unpvt
)
select dnorm.location, count(*) as total,
sum(case when dnorm.first_choice is not null then 1 else 0 end) as total2,
sum(case when dnorm.first_choice = 'SA' then 1 else 0 end) as SA,
. . .
from dnorm join
@TempLocation tl
on dnorm.location = tl.location
where ALL YOUR WHERE CONDITIONS HERE 动态SQL方法非常聪明,但我不认为这是实现这一目标的最简单方法。
https://stackoverflow.com/questions/13940066
复制相似问题