0

以下 SQl 生成以下结果表:

select ks2en, 
    count(case result when 'C-' then 1 end) as 'C-',
    count(case result when 'C' then 1 end) as 'C',
   count(case result when 'C+' then 1 end) as 'C+',
   count(case result when 'B' then 1 end) as 'B',
   count(case result when 'A' then 1 end) as 'A'
from student join subject 
on subject.upn=student.upn 
where name='English'
group by ks2en;

我想知道的是是否可以指定每一行的顺序。目前它的内容如下:

ks2en   C-  C   C+  B   A
        0   3   0   0   0
2a      0   0   0   0   0
3a      18  0   0   0   0
3b      0   0   0   0   0
3c      0   0   0   0   0
4a      3   11  1   1   0
4b      3   3   36  0   0
4c      1   26  0   0   0
5b      0   3   0   1   0
5c      3   12  4   33  0

我希望它如下所示:

ks2en   C-  C   C+  B   A
        0   3   0   0   0
2a      0   0   0   0   0
3c      0   0   0   0   0
3b      0   0   0   0   0
3a      18  0   0   0   0
4c      1   26  0   0   0
4b      3   3   36  0   0
4a      3   11  1   1   0
5c      3   12  4   33  0
5b      0   3   0   1   0

另一个注意事项是,根据结果,KS2en 列可能包含其他值,可能如下:

ks2en   

W
1c
1b
1a
2c
2b
2a      
3c      
3b      
3a      
4c      
4b      
4a      
5c      
5b      
5a
6c
6b
6a
4

1 回答 1

1

骇人听闻的方式(使用您的数据库提供的任何子字符串函数):

select 
    ks2en, 
    count(case result when 'C-' then 1 end) as 'C-',
    count(case result when 'C' then 1 end) as 'C',
    count(case result when 'C+' then 1 end) as 'C+',
    count(case result when 'B' then 1 end) as 'B',
    count(case result when 'A' then 1 end) as 'A'
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

数据库方式,使用列创建表(或向现有表添加列)ks2en, sequenceno,例如称为 ks2enSeq。为 ks2en 的每个值创建一行,按您想要的顺序使用升序序列号。

select 
    ks2en, 
    count(case result when 'C-' then 1 end) as 'C-',
    count(case result when 'C' then 1 end) as 'C',
    count(case result when 'C+' then 1 end) as 'C+',
    count(case result when 'B' then 1 end) as 'B',
    count(case result when 'A' then 1 end) as 'A'
from
    student 
        join 
    subject 
        on subject.upn = student.upn 
        inner join
    ks2enSeq k
        on k.ks2en = subject.ks2en
where 
    name='English'
group by 
    subject.ks2en
order by
    k.sequenceno
于 2013-09-20T19:40:15.803 回答