1. 程式人生 > >SQL分組查詢,子查詢

SQL分組查詢,子查詢

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_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:關聯中使用分組

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 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中使用子查詢

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

6: 建議不要在group by /order by /having中使用子查詢,但實質上是可以使用的。但可以在子查詢中使用分組函式,檢視上面例子;

以上為自己的學習總結,如果有不正確的地方歡迎朋友們指正,謝謝;