zoukankan      html  css  js  c++  java
  • (转)oracle group by 和order by的关系(在一起使用注意事项)

    转:http://lzfhope.blog.163.com/blog/static/636399220092554045196/

    环境:oracle 10g
    单单group by 或者order by本身没有特别好写的,因为这二者都是及其常用的sql句子的组成.
    通常order by 和group by 没有太多的关系,但是它们常常组合在一起用,完成分组加排序的功能.

    例如有下表:       

     SQL> select * from students;       
                          ID AREA       STU_TYPE                  SCORE
            ---------------- ---------- -------- ----------------------
                           1 111        g                         80.00
                           1 111        j                         80.00
                           2 111        g                         80.00
                           .......


    这个时候,执行这个语句是可以的:

     SQL> select stu_type,sum(score) from students group by stu_type;       
    STU_TYPE SUM(SCORE)
             -------- ----------
             j               542
             g               689

    但是如果执行下面这个语句,就会报告错误:

     SQL> select stu_type,sum(score) from students group by stu_type order by id;
    select stu_type,sum(score) from students group by stu_type order by id
    ORA-00979: 不是 GROUP BY 表达式

    正确的应该是这样的:

     SQL> select stu_type,sum(score) from students group by id,stu_type order by id;
    STU_TYPE SUM(SCORE)
    -------- ----------
    g               237
    j                80
    g               140
    j               135
    g               133
    j               148
    g               179
    j               179
    8 rows selected

    也许结果不是所愿,但是主要为了明白一个简单的道理:order by 中列,应该出现在group by 子句中。这是一个很显然的道理。

  • 相关阅读:
    内置函数详解
    关于内置函数
    ac自动机练习 HihoCoder 1036
    字典树Trie练习 HihoCoder 1014
    HDU 6170 Two String 动态规划
    NOJ 1190 约瑟夫问题 线段树OR树状数组
    NOJ 1186 灭蚊药水
    LightOJ 1085 树状数组+动态规划
    LightOJ 1066
    LightOJ 1080 树状数组
  • 原文地址:https://www.cnblogs.com/wangle1001986/p/3173787.html
Copyright © 2011-2022 走看看