如下的表结构:
要查询的结果中包含账户类型、开户雇员、开户行、及所有存储账户的余额求和。
常规的查法:
SELECT p.`name` product,b.`name` branch,
CONCAT(e.fname,'',e.lname) name,
SUM(a.avail_balance)
FROM account a INNER JOIN employee e
on a.account_id=e.emp_id
INNER JOIN branch b
on a.open_branch_id=b.branch_id
INNER JOIN product p
on a.product_cd=p.product_cd
WHERE p.product_type_cd='ACCOUNT'
GROUP BY p.`name`,b.`name`,e.fname,e.lname
ORDER BY 1,2
劣势分析,这里的分组是基于字符串的分组,而account表里面分别有对应的外键,可以按照外键进行分组,如:
--改进后的语句如下
SELECT
p.`name`,
b.`name`,
CONCAT(e.fname, ' ', e.lname),
account_groups.tot_deposits
FROM
(
SELECT
product_cd,
open_branch_id,
open_emp_id emp_id,
SUM(avail_balance) tot_deposits
FROM
account
GROUP BY
product_cd,
open_branch_id,
open_emp_id
) account_groups
INNER JOIN employee e ON e.emp_id = account_groups.emp_id
INNER JOIN branch b ON b.branch_id = account_groups.open_branch_id
INNER JOIN product p ON p.product_cd = account_groups.product_cd
WHERE
p.product_type_cd = 'ACCOUNT'