1. 程式人生 > >Oracle-查詢-分組函式練習

Oracle-查詢-分組函式練習

分組函式不能在where關鍵字後面使用

分組函式自動忽略空值

-- 查詢 employees 表中有多少個部門
SELECT e.department_id
FROM employees e
WHERE e.department_id IS NOT NULL
GROUP BY e.department_id;
-- HAVING e.department_id IS NOT NULL;

 

-- 查詢全公司獎金基數的平均值(沒有獎金的人按 0 計算)
SELECT AVG(NVL(e.commission_pct,0))
FROM employees e
-- 結果為:0.0728971962616822
SELECT AVG(e.commission_pct)
FROM employees e;
-- 結果為:0.222857142857143
-- 查詢各個部門的平均工資
SELECT e.department_id,AVG(e.salary)
FROM employees e
WHERE e.department_id IS NOT NULL
GROUP BY e.department_id

-- Toronto這個城市的員工的平均工資
SELECT AVG(e.salary)
FROM employees e
JOIN departments d
ON e.department_id = d.department_id
JOIN locations l
ON d.location_id = l.location_id
WHERE l.city = 'Toronto'
-- GROUP BY l.city
-- (有員工的城市)各個城市的平均工資
SELECT l.city,AVG(e.salary)
FROM employees e
JOIN departments d
ON e.department_id = d.department_id
JOIN locations l
ON d.location_id = l.location_id
GROUP BY l.city
-- 查詢平均工資高於 8000 的部門 id 和它的平均工資
SELECT e.department_id,AVG(e.salary)
FROM employees e
GROUP BY e.department_id
HAVING AVG(e.salary) > 8000;
-- 查詢平均工資高於 6000 的 job_title 有哪些
SELECT j.job_title,AVG(e.salary)
FROM employees e
JOIN jobs j 
ON e.job_id = j.job_id
GROUP BY j.job_title
HAVING AVG(e.salary) > 6000;
-- 查詢各個管理者手下員工的最低工資,其中最低工資不能低於6000,沒有管理者的員工不計算在內
SELECT  m.employee_id,MIN(e.salary) min_sal
FROM employees e
JOIN employees m
ON e.manager_id = m.employee_id
GROUP BY m.employee_id
HAVING MIN(e.salary) > 6000
-- 誰的工資比 Abel 高?
SELECT e.last_name,e.salary
FROM employees e
WHERE e.salary > (
                 SELECT emp.salary
                 FROM employees emp
                 WHERE emp.last_name = 'Abel'
               );
-- 查詢所有部門的名字,location_id,員工數量和工資平均值
SELECT e.department_id,d.location_id,COUNT(*) emp_num,AVG(e.salary)
FROM employees e
JOIN departments d
ON e.department_id = d.department_id
GROUP BY e.department_id,d.location_id