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 子句中。这是一个很显然的道理。

  • 相关阅读:
    git和TortoiseGit安装
    poi导出excel
    POI生成word文档
    java反编译工具
    如何把wecenter的推荐的问题模块单独调取出来?
    想学网站运营?我教你啊!(下)
    想学网站运营?我教你啊!(中)
    想学网站运营?我教你啊!(上)
    织梦模块管理里面空白
    Discuz/X3.1去掉标题中的Powered by Discuz!以及解决首页标题后的"-"
  • 原文地址:https://www.cnblogs.com/wangle1001986/p/3173787.html
Copyright © 2011-2022 走看看