-- 1)
SELECT
	emp_id,
	fname,
	lname
FROM employee
ORDER BY 
	lname DESC,
	fname;

-- 2)
SELECT 
	account_id,
	cust_id,
	avail_balance
FROM account
WHERE
	status = 'ACTIVE'
AND
	avail_balance > 2500;

-- 3)
SELECT DISTINCT(open_emp_id)
FROM account;

-- 4)
SELECT COUNT(account_id)
FROM account;

-- 5)
SELECT 
	individual.fname,
	individual.lname, 
	COUNT(*)
FROM individual
JOIN account
	ON individual.cust_id = account.cust_id
GROUP BY 
	individual.fname,
	individual.lname;

-- 6)
SELECT 
	individual.fname,
	individual.lname, 
	COUNT(*)
FROM account
JOIN individual
	ON account.cust_id = individual.cust_id
GROUP BY 
	individual.fname,
	individual.lname
HAVING
	COUNT(*) >= 2;

-- 7)
SELECT *
FROM account
WHERE EXTRACT(YEAR FROM open_date) = 2002;

-- 8)
SELECT *
FROM individual
WHERE lname LIKE '_a%e%';

-- 9)
SELECT 
	account.account_id, 
	customer.fed_id,
	product.name
FROM account
JOIN individual
	ON account.account_id = individual.cust_id
JOIN customer
	ON account.account_id = customer.cust_id
JOIN product
	ON account.product_cd = product.product_cd;

-- 10)
SELECT 
	e.emp_id,
	e.fname,
	e.lname
FROM employee e
JOIN employee s
	ON e.superior_emp_id = s.superior_emp_id
JOIN department d1
	ON e.dept_id = d1.dept_id
JOIN department d2
	ON s.superior_emp_id = d2.dept_id
WHERE d1.dept_id <> d2.dept_id;

-- 11)
SELECT
	i.fname,
	i.lname
FROM individual i
UNION
SELECT
	e.fname,
	e.lname
FROM employee e;

-- 12)
SELECT
	s.fname || ' ' || s.lname AS superior,
	STRING_AGG(e.fname || ' ' || e.lname, ', ') AS employees
FROM employee s
JOIN employee e
	ON e.superior_emp_id = s.emp_id
GROUP BY s.fname, s.lname;

-- 13)
SELECT
	a.account_id,
	a.cust_id,
	COALESCE(b.name, i.fname || ' ' || i.lname)
FROM account a
JOIN customer c
	ON a.cust_id = c.cust_id
LEFT JOIN business b
	ON c.cust_id = b.cust_id
LEFT JOIN individual i
	ON c.cust_id = i.cust_id;

-- 14)
SELECT
	COALESCE(b.name, i.fname || ' ' || i.lname) customer_name
FROM (
		SELECT 
			cust_id, 
			SUM(avail_balance) AS balance
		FROM account
		GROUP BY cust_id
		ORDER BY balance DESC
		LIMIT 1
	) top_customer
JOIN customer c
	ON top_customer.cust_id = c.cust_id
LEFT JOIN business b
	ON c.cust_id = b.cust_id
LEFT JOIN individual i
	ON c.cust_id = i.cust_id;

-- 15)
SELECT 
	a.account_id, 
	p.name
FROM account a
FULL JOIN product p
	ON a.product_cd = p.product_cd