Oracle 在使用pivot时,注意事项

时间:2021-05-08 07:40:22

a)         Pivot的时候,实际上也是一次分组,并且可以通过聚簇函数来实现统计

b)         Pivot在取列名的时候,如果别名有汉字,要用双引号括起来,或者不用双引号

c)         如果对应的字段值为非数字或者字母,记得要用单引号引起来,比如下面的’A’

select *

  from (select case

                 when a.score >= 220 and a.score <= 330 then

                  '(220,330)'

                 when a.score >= 630 and a.score <= 710 then

                  '(630,710)'

                 when a.score < 220 then

                  '其他'

                 else

                  '(' || (ceil((a.score - 330) / 20) * 20 + 330) || ',' ||

                  (ceil((a.score - 330) / 20 + 1) * 20 + 330) || ')'

              

               end 分数段,

               b.score

          from SUBJECTREGISTER a

          left join SUBJECTREGISTER b

            on a.candidatesid = b.candidatesid

         WHERE a.testid = '181'

           and a.CAMPUSCODE LIKE '12%'

           AND a.SUBJECTCODE != 'S'

           AND a.SUBJECTCODE != 'F'

           AND (a.SCORE != '0' AND a.SCORE IS NOT NULL and

               b.score IS NOT NULL)

           AND (b.SUBJECTCODE = 'S' or b.SUBJECTCODE = 'F')) pivot(count(SCORE) FOR SCORE IN('A' "A",

                                                                                             'A+' "A+",

                                                                                             'B' "B",

                                                                                             'B+' "B+",

                                                                                             'C' "C",

                                                                                             'C+' "C+",

                                                                                             'D' "D",

                                                                                             'D+' "D+"))

 ORDER BY 分数段