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

  • 相关阅读:
    软件开发目录规范
    编译Python文件
    python文件的两种用途
    函数高级实战之ATM和购物车系统升级
    函数高级小结
    SpringCloud---(4)Eureka与Zookeeper的区别
    Maven父工程(统一管理依赖)
    SpringCloud-----(1)微服务基础概念
    传统项目架构图
    Session
  • 原文地址:https://www.cnblogs.com/wangle1001986/p/3173787.html
Copyright © 2011-2022 走看看