Use multiple CTEs to perform a comprehensive customer analysis: calculate total spending and invoice count, then combine them.
Write a query with two CTEs: one for total spending, one for invoice counts. Then join them in the final query.
| Column | Type |
|---|---|
| CustomerId | INTEGER (Primary Key) |
| FirstName | TEXT |
| LastName | TEXT |
| Company | TEXT |
| Address | TEXT |
| City | TEXT |
| State | TEXT |
| Country | TEXT |
| PostalCode | TEXT |
| Phone | TEXT |
| Fax | TEXT |
| TEXT | |
| SupportRepId | INTEGER (Foreign Key → Employee.EmployeeId) |
| Column | Type |
|---|---|
| InvoiceId | INTEGER (Primary Key) |
| CustomerId | INTEGER (Foreign Key → Customer.CustomerId) |
| InvoiceDate | TIMESTAMP |
| BillingAddress | TEXT |
| BillingCity | TEXT |
| BillingState | TEXT |
| BillingCountry | TEXT |
| BillingPostalCode | TEXT |
| Total | NUMERIC(10,2) |
WITH cte1 AS (...),
cte2 AS (...)
SELECT ... FROM cte1 JOIN cte2 ...;
Ready to take your skills to the next level? Enroll in our comprehensive Data Analyst Career Track to master SQL, Python, Excel, and Power BI.
Run your code to see the result here.