Oracle SQL Group By Upper

时间:2017-01-17 04:23:43

标签: sql oracle

我有3个数据库表,我想在我的SQL查询中使用它:

问题是,我想对MYMAINSCHEMA.SURVEY表中的“学校名称”值进行GROUP BY。但是,“学校名称”有时可以是大写或小写。

这是我的SQL:

select SR.SCHOOL_NUM,UPPER(S.SCHOOLNAME), COUNT(S.SWSID) AS NUMSTUDENTS 
from MYMAINSCHEMA.SURVEY S 
JOIN MYOTHERSCHEMA.SCHOOL_RTO SR ON S.SCHOOLCODE = SR.SCHOOL_NUM
JOIN  MYOTHERSCHEMA.RTO R ON R.RTO_NUM = SR.RTO_NUM 
GROUP BY SR.SCHOOL_NUM,UPPER(S.SCHOOLNAME)
ORDER BY S.SCHOOLNAME ASC;

运行上面的代码给出了错误“不是GROUP BY表达式”。 如果我删除第1行和第2行中的UPPER,它可以正常工作,但结果会返回重复的SCHOOL名称(一些是大写的,一些是小写的)。

有没有解决这个问题?

先谢谢。

2 个答案:

答案 0 :(得分:1)

试试这个:

select SR.SCHOOL_NUM,
  UPPER(S.SCHOOLNAME) SCHOOLNAME, -- added alias here
  COUNT(S.SWSID) AS NUMSTUDENTS 
from MYMAINSCHEMA.SURVEY S 
JOIN MYOTHERSCHEMA.SCHOOL_RTO SR ON S.SCHOOLCODE = SR.SCHOOL_NUM
JOIN  MYOTHERSCHEMA.RTO R ON R.RTO_NUM = SR.RTO_NUM 
GROUP BY SR.SCHOOL_NUM,UPPER(S.SCHOOLNAME)
ORDER BY SCHOOLNAME ASC;  -- fixed here by sorting on the alias
                          -- (can use "UPPER(S.SCHOOLNAME)")

聚合中使用UPPER(S.SCHOOLNAME)。因此,S.SCHOOLNAME无法订购。使用UPPER(S.SCHOOLNAME),别名或列号。

答案 1 :(得分:1)

问题是ORDER BY。也可以在那里使用UPPER()

ORDER BY UPPER(S.SCHOOLNAME) ASC;

如果我认为school_num实际上是唯一的,那么我可能会建议:

select SR.SCHOOL_NUM, MAX(UPPER(S.SCHOOLNAME)),
        COUNT(S.SWSID) AS NUMSTUDENTS 
from MYMAINSCHEMA.SURVEY S join
     MYOTHERSCHEMA.SCHOOL_RTO SR 
     on S.SCHOOLCODE = SR.SCHOOL_NUM join
     MYOTHERSCHEMA.RTO R 
     on R.RTO_NUM = SR.RTO_NUM 
group by SR.SCHOOL_NUM
order by MAX(UPPER(S.SCHOOLNAME)) ASC;