select格式
SELECT [ ALL | DISTINCT ] <字段表达式1[,<字段表达式2[,…]
FROM <表名1>,<表名2>[,…]
[WHERE <筛选择条件表达式>]
[GROUP BY <分组表达式> [HAVING<分组条件表达式>]]
[ORDER BY <字段>[ASC | DESC]]

语句说明
[]方括号为可选项
[GROUP BY <分组表达式> [HAVING<分组条件表达式>]]
指将结果按<分组表达式>的值进行分组,该值相等的记录为一组,带【HAVING】
短语则只有满足指定条件的组才会输出。
[ORDER BY <字段>[ASC | DESC]]
显示结果要按<字段>值升序或降序进行排序

sql各子句的执行顺序:            

1. FROM
2. WHERE
3. GROUP BY
4. HAVING
5. SELECT
6. ORDER BY
 



练习:
1:表hkb_test_sore取出成绩sore前5名的记录,
2:取第5名的记录
1,答案select a.sore_id, a.sore
  from (select * from hkb_test_sore order by sore desc) a
 where rownum <=5

2,答案select a.sore_id, a.sore
  from (select * from hkb_test_sore order by sore desc) a
 where rownum <=5
 minus
select a.sore_id, a.sore
  from (select * from hkb_test_sore order by sore desc) a
 where rownum <=4;
3:查询两个分数一样的记录
select *
  from hkb_test_sore a
 where a.sore = (select sore
                   from hkb_test_sore a
                  group by a.sore
                 having count(a.sore) = 2);

union,union all,intersect,minus的区别:
SQL> select * from hkb_test2;
X        Y
---- -----
a        1
b        2
c        3
g        4

SQL> select * from hkb_test3; 
X        Y
---- -----
a        1
b        2
e        3
f        4
 
SQL> select * from hkb_test2;
X        Y
---- -----
a        1
b        2
c        3
g        4
 
SQL> select * from hkb_test3;
X        Y
---- -----
a        1
b        2
e        3
f        4
 
SQL> select * from hkb_test2
  2  union
  3  select * from hkb_test3;
X        Y
---- -----
a        1
b        2
c        3
e        3
f        4
g        4
 
6 rows selected
 
SQL> select * from hkb_test2
  2  union all
  3  select * from hkb_test3;
X        Y
---- -----
a        1
b        2
c        3
g        4
a        1
b        2
e        3
f        4
 
8 rows selected

SQL> select * from hkb_test2
  2  intersect
  3  select * from hkb_test3;
X        Y
---- -----
a        1
b        2
 
SQL> select * from hkb_test2
  2  minus
  3  select * from hkb_test3;
X        Y
---- -----
c        3
g        4

posted on 2007-08-23 16:18  简单男人!  阅读(7913)  评论(0编辑  收藏  举报