Chapter 7 · CTEs
19. Customer Spending by Category (CTE with Percentages)
Hard40 XPFinance
Build a spending breakdown by transaction type for each customer. CTE 1: customer_totals — total transaction amount per customer. CTE 2: type_totals — total amount per customer per transaction type. Main query: join both to compute the percentage of spend in each type. Return first_name, last_name, type, type_amount, total_amount, and spend_pct rounded to 1 decimal. Sort by last_name, spend_pct descending. Limit to 50.
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
- FKaccount_id→ accounts.idINT
- transaction_dateTEXT
- typeTEXT
- amountREAL
- balance_afterREAL
- descriptionTEXT
- reference_numberTEXT
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.