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

  • 相关阅读:
    codevs 3641 上帝选人
    codevs 1966 乘法游戏
    codevs 1345 饥饿的奶牛
    codevs 1962 马棚问题--序列型DP
    codevs 1959 拔河比赛--判断背包内刚好装满n/2个物品
    codevs 1297 硬币
    [转载]矩阵取数游戏
    101.金明的预算方案(分组背包)
    105.(并查集结合绝对值最小的01背包)选学霸
    POJ 2528 Mayor's posters(线段树)
  • 原文地址:https://www.cnblogs.com/wangle1001986/p/3173787.html
Copyright © 2011-2022 走看看