Chapter 7 · CTEs
17. Customer Account Summary with Multiple CTEs
Hard40 XPFinance
Build a comprehensive customer summary. CTE 1: account_summary — count accounts and sum balances per customer. CTE 2: loan_summary — count loans and sum principal per customer. Main query: join both CTEs to customers. Return first_name, last_name, account_count, total_balance, loan_count, total_principal. Include customers even if they have no loans. Sort by total_balance descending. Limit to 20.
Tables
- PKidINT
- first_nameTEXT
- last_nameTEXT
- emailTEXT
- phoneTEXT
- date_of_birthTEXT
- cityTEXT
- stateTEXT
- countryTEXT
- created_atTIMESTAMP
- PKidINT
- FKcustomer_id→ customers.idINT
- account_typeTEXT
- balanceREAL
- currencyTEXT
- opened_atTEXT
- statusTEXT
- PKidINT
- FKcustomer_id→ customers.idINT
- loan_typeTEXT
- principalREAL
- interest_rateREAL
- term_monthsINT
- start_dateTEXT
- statusTEXT
Need help?
Ask Sol
AI tutor — looks at your current query and nudges you, without spoiling the answer.
Solution
Try the hints first — solving it yourself is what makes it stick.