How can you write a SQL query to get department names and their total revenue for the past year?
Ready to answer it out loud?
Run a mock interview on this exact question and get instant AI feedback.
Question Explain
To write a SQL query that retrieves all department names along with their total revenue over the past twelve months, you would typically follow these steps:
-
Identify the Necessary Tables and Columns: Make sure you know which tables contain the department names and revenue data. Typically, you might have a
departmentstable and asalestable, with thesalestable including a column for revenue and a timestamp or date column to filter the last twelve months. -
Use the SELECT Statement: Begin your query with a
SELECTstatement to specify the columns you want to retrieve, which are the department names and the sum of their revenues. -
Join the Tables: Use a
JOINclause to combine thedepartmentstable with thesalestable based on a common key, such asdepartment_id. -
Filter the Date Range: Use a
WHEREclause to filter the data to only include sales from the past twelve months. This can be done using date functions likeNOW()andINTERVAL. -
Group and Aggregate the Data: Use the
GROUP BYclause to group the results by department name and theSUM()function to calculate the total revenue for each department. -
Order the Results (Optional): If desired, you can use an
ORDER BYclause to sort the results, for example, by total revenue in descending order.
Here is a sample SQL query that puts all of these steps together:
SELECT
d.department_name,
SUM(s.revenue) AS total_revenue
FROM
departments d
JOIN
sales s ON d.department_id = s.department_id
WHERE
s.sale_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
GROUP BY
d.department_name
ORDER BY
total_revenue DESC;
Explanation of the Query:
SELECT d.department_name, SUM(s.revenue) AS total_revenue: This selects the department names and calculates the sum of their revenues, labeling it astotal_revenue.FROM departments d JOIN sales s ON d.department_id = s.department_id: This joins thedepartmentstable with thesalestable on thedepartment_idfield.WHERE s.sale_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH): This filters the records to include only those with asale_datewithin the last twelve months.GROUP BY d.department_name: This groups the results by department name so that theSUM()function calculates the total revenue for each department.ORDER BY total_revenue DESC: This orders the results by total revenue in descending order, so the department with the highest revenue appears first.
Make sure to adjust table names, column names, and the date filtering logic according to your actual database schema and requirements.
Answer Example
To write a SQL query that retrieves the department names along with their total revenue for the past twelve months, you would follow these steps:
-
Identify Tables and Columns: First, determine which tables contain the necessary data. You will likely have a
departmentstable containing department names and asalestable with columns for revenue and a sale date, which will allow you to filter sales data from the last twelve months. -
Use the SELECT Statement: Start your query by deciding which columns to include. Here, you need department names and total revenue for each department.
-
Join the Tables: Perform a JOIN on the
departmentsandsalestables based on a common identifier, such asdepartment_id. -
Filter by Date: Use a
WHEREclause to select only the sales records from the past twelve months. This can typically be done using date manipulation functions likeDATE_SUB()in combination withCURDATE(). -
Group and Aggregate Data: Utilize the
GROUP BYclause to organize the results by department. Apply theSUM()function to aggregate revenue data for each department. -
Order the Results (Optional): To arrange the output in descending order of revenue, use an
ORDER BYclause.
Here is an example SQL query that implements these steps:
SELECT
d.department_name,
SUM(s.revenue) AS total_revenue
FROM
departments d
JOIN
sales s ON d.department_id = s.department_id
WHERE
s.sale_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
GROUP BY
d.department_name
ORDER BY
total_revenue DESC;
Explanation of the Query Components:
-
SELECT d.department_name, SUM(s.revenue) AS total_revenue: This line specifies that you want to select department names and compute the sum of revenues, labeling the sum astotal_revenue. -
FROM departments d JOIN sales s ON d.department_id = s.department_id: This portion links thedepartmentsandsalestables using an INNER JOIN on thedepartment_id. This ensures each sales record is associated with the correct department. -
WHERE s.sale_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH): This condition filters sales data to include only those records within the last twelve months, ensuring you focus on the relevant time period. -
GROUP BY d.department_name: This clause groups all selected records by the department name, which is necessary to calculate revenue totals for each department separately. -
ORDER BY total_revenue DESC: This orders the results so that departments with the highest revenue appear at the top of your results.
This query provides an accurate, organized view of department revenue over the past year, suitable for business analysis or reporting. Adjust table names and column fields as necessary to align with your specific database schema.