cswork / libraryOpen practice workspace

Coding questions · Amazon

Create Monthly Revenue Report for Each Department

This question evaluates proficiency in SQL data transformation and aggregation, specifically the ability to pivot row-level transactional revenue into a columnar monthly report and handle schema alignment for reporting.

DEPARTMENT_REVENUE

+------------+---------+-------+
| Department | Revenue | Month |
+------------+---------+-------+
| A          | 8000    | Jan   |
| B          | 9000    | Jan   |
| C          | 10000   | Feb   |
| A          | 7000    | Feb   |
| A          | 6000    | Mar   |
+------------+---------+-------+
Scenario

Finance analytics team needs a report that shows each department in one row with separate revenue columns for every month of the year.

Question

Given table DEPARTMENT_REVENUE(Department, Revenue, Month), write an SQL query that pivots the data so the output has one row per department and twelve columns: Jan_Revenue, Feb_Revenue, …, Dec_Revenue.

Hints

Use conditional aggregation (CASE) or database-specific PIVOT operator.

Pivot Monthly Revenues With Annual Total

The finance analytics team needs a report that shows each department in one row with separate revenue columns for every month of the year and an annual total.

Given table DEPARTMENT_REVENUE(Department, Revenue, Month), where Month is a three-letter abbreviation from 'Jan' to 'Dec', write an SQL query that pivots the data so the output has one row per department and twelve columns: Jan_Revenue, Feb_Revenue, …, Dec_Revenue. Months with no revenue for a department should appear as 0. Also include an Annual_Total column that is the sum of that department's revenue across all months.

Table DEPARTMENT_REVENUE

columntypeconstraints
DepartmentVARCHAR(10)
RevenueINTEGER
MonthVARCHAR(3)

Sample data:

DepartmentMonthRevenue
AJan8000
BJan9000
CFeb10000
AFeb7000
AMar6000

Expected output

One row per department with revenue columns for each month (Jan through Dec). Months with no revenue should be shown as 0. Include an Annual_Total column summing all revenue for that department.

Annual_TotalApr_RevenueAug_RevenueDec_RevenueDepartmentFeb_RevenueJan_RevenueJul_RevenueJun_RevenueMar_RevenueMay_RevenueNov_RevenueOct_RevenueSep_Revenue
21000000A700080000060000000
9000000B090000000000
10000000C1000000000000

Hints

  1. Use conditional aggregation with SUM and CASE to build each month column.
  2. Use ELSE 0 in the CASE expression (or wrap SUM with COALESCE) so missing months appear as 0.
  3. Annual_Total can be computed as SUM(Revenue) per Department.