Prepin
Log in

Sales by Customer Location

Approach / Explanation

This SQL question requests that you create a query to compute the total sales values categorized by city from a sales database. This task will likely require the use of aggregate functions such as SUM() and GROUP BY . Here’s how to tackle this question: Familiarize Yourself with the Database Schema: To respond to this question, it's essential to first understand the database schema. There should be a sales table that logs each transaction, which includes the sales amount and a reference to the customer involved. Additionally, there should be a customers table that contains customer information, including their city of residence. Join the Relevant Tables: Since the sales data and customer information are likely stored in distinct tables, you will need to join these tables on the appropriate column (likely customer_id ) to obtain the necessary data. Aggregate Sales by City: Once the tables are joined, you can calculate the total sales for each customer city using the GROUP BY clause along with the SUM() aggregate function in SQL. Sort the Results: It is generally advisable to sort the results in descending order based on the total sales amount, unless the question specifies otherwise. This can be accomplished with the ORDER BY clause in SQL.

Suggested Answer

Below is an example of how to respond to this question: SELECT c . city , SUM ( s . sales_amount ) as total_sales FROM sales s JOIN customers c ON s . customer_id = c . customer_id GROUP BY c . city ORDER BY total_sales DESC ; This SQL query combines the sales table (referenced as s ) with the customers table (referenced as c ) based on the customer_id column. It then organizes the results by city ( c.city ) and calculates the total sales amounts ( s.sales_amount ). The total sales are referred to as total_sales , and the final results are sorted by total_sales in descending order.

Alternative Answer

Here’s another method to respond, utilizing subqueries rather than a join: SELECT c . city , ( SELECT SUM ( s . sales_amount ) FROM sales s WHERE s . customer_id = c . customer_id ) as total_sales FROM customers c ORDER BY total_sales DESC ; This SQL query employs a subquery to compute the total sales for each customer. The subquery runs for each entry in the customers table, and the results are then sorted in descending order based on total_sales .

Question Details

Difficulty & Category

Medium
sql

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.