postgreSQL高階功能_02
-- 測試表
CREATE TABLE employees (
employee_id serial PRIMARY KEY,
employee_name VARCHAR (255) NOT NULL
);
CREATE TABLE keys (
employee_id INT PRIMARY KEY,
effective_date DATE NOT NULL,
FOREIGN KEY (employee_id) REFERENCES employees (employee_id)
);
CREATE TABLE hipos (
employee_id INT PRIMARY KEY,
effective_date DATE NOT NULL,
FOREIGN KEY (employee_id) REFERENCES employees (employee_id)
);
-- 測試資料
INSERT INTO employees (employee_name)
VALUES
('Joyce Edwards'),
('Diane Collins'),
('Alice Stewart'),
('Julie Sanchez'),
('Heather Morris'),
('Teresa Rogers'),
('Doris Reed'),
('Gloria Cook'),
('Evelyn Morgan'),
('Jean Bell');
INSERT INTO keys
VALUES
(1, '2000-02-01'),
(2, '2001-06-01'),
(5, '2002-01-01'),
(7, '2005-06-01');
INSERT INTO hipos
VALUES
(9, '2000-01-01'),
(2, '2002-06-01'),
(5, '2006-06-01'),
(10, '2005-06-01');
select employee_id from keys
select employee_id from hipos
select employee_id from keys
-- 返回交集,同時存在兩個表查詢出來的資料
intersect
select employee_id from hipos
order by employee_id desc
select employee_id from keys
-- 返回並集
union
select employee_id from hipos
select employee_id from keys
-- 返回差集,
except
select employee_id from hipos
---------------- ---------------------
CREATE TABLE sales (
brand VARCHAR NOT NULL,
segment VARCHAR NOT NULL,
quantity INT NOT NULL,
PRIMARY KEY (brand, segment)
);
INSERT INTO sales (brand, segment, quantity)
VALUES
('ABC', 'Premium', 100),
('ABC', 'Basic', 200),
('XYZ', 'Premium', 100),
('XYZ', 'Basic', 300);
select * from sales;
select brand,sum(quantity) from sales group by brand;
select segment,sum(quantity) from sales group by segment;
select sum(quantity) from sales;
-- 分組集 grouping sets
-- 這個有點不實用,但留個印象,存在即合理
select brand,segment,sum(quantity) from sales
group by grouping sets ((brand,segment),(brand),(segment),());
select grouping(brand) as grouping_brand,grouping(segment) as grouping_segment,brand,segment,sum(quantity) from sales
group by grouping sets ((brand,segment),(brand),(segment),()) order by brand,segment;
-- cube 在 grouping sets 的基礎上進行的簡化操作,會生成所有可能的分組集
select brand,segment,sum(quantity) from sales
group by cube (brand,segment);
select grouping(brand) as grouping_brand,grouping(segment) as grouping_segment,brand,segment,sum(quantity) from sales
group by cube (brand,segment) order by brand,segment;
-- rollup 在其上進行快捷的操作
select brand,segment,sum(quantity) from sales
group by rollup (brand,segment);
-- 下面sql查詢的分組集有
-- (segment,brand)
-- (segment)
-- ()
select brand,segment,sum(quantity) from sales
group by rollup (segment,brand);
-- EXTRACT() 函式用於返回日期/時間的單獨部分
select * from rental;
select extract(year from rental_date) as y,count(rental_id) from rental group by rollup(extract(year from rental_date))
___________________________________________________
-- 子查詢
select AVG(rental_rate) from film;
select film_id,title,rental_rate from film where rental_rate > 2.98
select film_id,title,rental_rate from film where rental_rate > (select avg(rental_rate) from film);