SQL分组查询,子查询

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

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

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

2: 分组函数与分组查询

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

分组查询格式及示例

// 分组查询格式
SELECT   column或 group_function
FROM     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:关联中使用分组express

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:三表查询app

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子句:svg

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

所以当须要加上过滤条件,过滤条件又是汇集函数那就要使用having关键字做为having子句了;函数

子查询/嵌套查询

1: 子查询语法

SELECT select_list FROM table WHERE 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中使用子查询spa

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

2.在from中使用子查询code

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

3.在where中使用子查询xml

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_list FROM table WHERE expr operator ( SELECT select_list FROM table );

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

以上为本身的学习总结,若是有不正确的地方欢迎朋友们指正,谢谢;