SQL指定动态行值的顺序

时间:2013-09-20 19:32:05

标签: sql group-by sql-order-by

以下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

1 个答案:

答案 0 :(得分:1)

hacky方式(使用db提供的任何子字符串函数):

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