Sql server 2008 SQL优化选择案例语句
是否有可能简化以下案例陈述,或者我已经以最优雅的形式提供了它Sql server 2008 SQL优化选择案例语句,sql-server-2008,optimization,coding-style,case,Sql Server 2008,Optimization,Coding Style,Case,是否有可能简化以下案例陈述,或者我已经以最优雅的形式提供了它 select case when Ks2en = '' then 'No KS2' else ks2en end as 'KS2', nullif(count(case result when '' then 1 end),0) as 'No Result', nullif(count(case result when 'U' then 1 when '1a' then 1 when '1b' then 1
select case when Ks2en = '' then 'No KS2' else ks2en end as 'KS2',
nullif(count(case result when '' then 1 end),0) as 'No Result',
nullif(count(case result when 'U' then 1 when '1a' then 1 when '1b' then 1 when '1c' then 1 end),0) as '1/U',
nullif(count(case result when 'U' then 1 when '2a' then 1 when '2b' then 1 when '2c' then 1 end),0) as '2/U',
nullif(count(case result when 'G-' then 1 when '3c' then 1 end),0) as '3c/G-',
nullif(count(case result when 'G' then 1 when '3b' then 1 end),0) as '3b/G',
nullif(count(case result when 'G+' then 1 when '3a' then 1 end),0) as '3a/G+',
nullif(count(case result when 'F-' then 1 when '4c' then 1 end),0) as '4c/F-',
nullif(count(case result when 'F' then 1 when '4b' then 1 end),0) as '4b/F'
**snip**
from student join subject
on subject.upn=student.upn
where name='English'
group by ks2en
order by
case when ks2en = 'W' Then 0 Else 1 End,
left(ks2en, 1),
right(ks2en, 1) desc
它生成以下网格,我希望此结果保持不变:
KS2 No Result 1/U 2/U 3c/G- 3b/G 3a/G+ 4c/F- 4b/F **snip**
No KS2 1 NULL NULL NULL NULL NULL NULL **snip**
2a NULL NULL NULL NULL NULL NULL 2 1 **snip**
3c 1 NULL NULL NULL NULL NULL NULL NULL **snip**
3b NULL NULL NULL NULL NULL NULL 1 NULL **snip**
3a 1 NULL NULL NULL NULL NULL NULL NULL **snip**
4c NULL 1 1 NULL NULL NULL NULL NULL **snip**
4b NULL NULL NULL NULL NULL NULL NULL NULL **snip**
4a NULL 1 1 NULL NULL NULL NULL NULL **snip**
5c NULL NULL NULL NULL NULL NULL NULL NULL **snip**
5b NULL NULL NULL NULL NULL NULL NULL NULL **snip**
为了简洁起见,我删掉了代码和结果,但是sql包含了更多的案例,以便创建总计列。我不认为这段代码提高了性能,所以我发布了一种不同的方法,IMO更优雅。我正在使用
结果([ListoOptions])
而不是多个案例。。。当
,我认为执行不会有太大变化
select case when Ks2en = '' then 'No KS2' else ks2en end as 'KS2',
nullif(count(case when result = '' then 1 end),0) as 'No Result',
nullif(count(case when result IN ('U', '1a', '1b', '1c') then 1 end),0) as '1/U',
nullif(count(case when result IN ('U', '2a', '2b', '2c') then 1 end),0) as '2/U',
nullif(count(case when result IN ('G-','3c') then 1 end),0) as '3c/G-',
nullif(count(case when result IN ('G', '3b') then 1 end),0) as '3b/G',
nullif(count(case when result IN ('G+','3a') then 1 end),0) as '3a/G+',
nullif(count(case when result IN( 'F-','4c') then 1 end),0) as '4c/F-',
nullif(count(case when result IN( 'F', '4b') then 1 end),0) as '4b/F'
from student
inner join subject
on subject.upn=student.upn
where name='English'
group by ks2en
order by
case when ks2en = 'W' Then 0 Else 1 End,
left(ks2en, 1),
right(ks2en, 1) DESC
SQL只是结构化查询语言-一种被许多数据库系统使用的语言,但不是一种数据库产品。。。很多东西都是特定于供应商的-所以我们真的需要知道您使用的是什么数据库系统(以及哪个版本)(请相应地更新标签)。。。。