SQL分组查询,子查询

来源:互联网 发布:翔云软件 编辑:程序博客网 时间:2024/06/06 10:53

1: 分组函数/又称聚集函数

1.分组函数(默认情况下就是ALL)

AVG   (DISTINCT |ALL| n)COUNT (DISTINCT |ALL| expr | *) // NULL不计算,但对数字0计算MAX   (DISTINCT |ALL| expr)MIN   (DISTINCT |ALL| expr)SUM   (DISTINCT |ALL| n)

2: 分组函数与分组查询

分组与分组函数的使用要明确,查什么, 从哪查询, 目标关联,是否需要分组;

分组查询格式及示例

// 分组查询格式SELECT   column或 group_functionFROM     table[WHERE   condition][GROUP BY  group_by_expression][HAVING    group_condition] // 过滤条件为聚集函数,使用having[ORDER BY  column];// 分组查询示例SQL> SELECT    title, SUM(salary) PAYROLL    FROM    s_emp    WHERE    title NOT LIKE 'VP%'    GROUP BY    title    HAVING    SUM(salary) > 5000    ORDER BY    SUM(salary);

例子:

1:关联中使用分组

select s_region.name, count(s_dept.id) from     s_dept, s_region    where s_dept.region_id = s_region.id     group by s_region.name;

2:三表查询

select r.name, count(e.id) from s_region r,     s_dept d, s_emp e    where r.id = d.region_id and d.id = e.dept_id    group by r.name

分组/聚集函数使用位置注意事项:

在select中可以使用分组函数,在where子句中不能使用分组函数,因此出现了having子句:

having 过滤条件 
// 1. 错误的,where中不能出现分组函数 select d.name , avg(e.salary) from s_dept d, s_emp ewhere d.id = e.dept_idgroup by d.nameand avg(e.salary) > 1000; // 2.正确, having 紧跟 group by select d.name , avg(e.salary) from s_dept d, s_emp ewhere d.id = e.dept_idgroup by d.namehaving avg(e.salary) > 1000

因此当需要加上过滤条件,过滤条件又是聚集函数那就要使用having关键字作为having子句了;

子查询/嵌套查询

1: 子查询语法

SELECT    select_listFROM    tableWHERE    expr operator(    SELECT    select_list     FROM        table);

2: 子查询示例

select first_name from s_emp where id **=** (    select managet_id from s_emp where id = 2);

3: 子查询的应用

注意 : 子查询中的括号( )不能省略;

1.在select中使用子查询

select first_name,     (        select name from s_dept where              s_dept.id = s_emp.dept_id     )from s_emp;

2.在from中使用子查询

select id, first_name from  (     select * from s_emp where commission_pct is null  )where salary >=1000;

3.在where中使用子查询

select first_name from s_emp where id = (    select managet_id from s_emp where id = 2 );

建议不要在group by /order by /having中使用子查询,但实质上是可以使用的。
但可以在子查询中使用分组函数
比如:

select first_name from s_emp where salary >=  (      select avg(salary) from s_emp );  // Right

子查询前的运算符或关键字可以为in / not in / = / <> / >= / > 等等;

小结与注意:

1: 聚集函数一般与分组操作一起使用;
2: 在含有group by的分组功能的select语句中,select列表中出现的字段要么出现在group by中,要么出现在分组函数中.
3: 当需要加上过滤条件,过滤条件又是聚集函数那就要使用having关键字了;
4: select完整用法示例

select   查询内容    from     哪里查询    where    关联关系             and过滤条件        group by 分组方式     having   分组过滤     order by 排序// 分组过滤是采用having,即过滤条件为上面的聚集/分组函数

5: 子查询语法

SELECT    select_listFROM    tableWHERE    expr operator    (        SELECT    select_list  FROM        table    );

6: 建议不要在group by /order by /having中使用子查询,但实质上是可以使用的。但可以在子查询中使用分组函数,查看上面例子;

以上为自己的学习总结,如果有不正确的地方欢迎朋友们指正,谢谢;

0 0
原创粉丝点击