Interview question
Build daily order KPIs with conditional aggregation
Builds several daily business metrics in one grouped query while keeping each metric definition explicit.
TL;DR
Builds several daily business metrics in one grouped query while keeping each metric definition explicit.
Conditional aggregation, metric definitions, null-safe sums, date boundaries, and report query shape.
Practice the problem like a real interview: restate, reason, implement, and test.
Table: Orders(OrderId, CreatedAtUtc, Status, TotalAmount). Return one row per UTC calendar date in [FromUtc, ToUtc): total orders, paid orders, cancelled orders, and revenue from paid orders. Dates with no orders do not need a row.
For a day with two paid orders worth 25 and 75 plus one cancelled order, return total 3, paid 2, cancelled 1, and paid revenue 100.
I filter on the raw timestamp so the range can use an index, then convert the remaining rows to a UTC date for grouping. Each KPI gets its own CASE expression, which keeps the business definition visible. ELSE 0 prevents null arithmetic and makes days containing no paid orders return zero revenue.
SELECT
CONVERT(date, o.CreatedAtUtc) AS OrderDate,
COUNT_BIG(*) AS TotalOrders,
SUM(CASE WHEN o.Status = 'Paid' THEN CONVERT(bigint, 1) ELSE 0 END) AS PaidOrders,
SUM(CASE WHEN o.Status = 'Cancelled' THEN CONVERT(bigint, 1) ELSE 0 END) AS CancelledOrders,
SUM(CASE
WHEN o.Status = 'Paid' THEN o.TotalAmount
ELSE CONVERT(decimal(18, 2), 0)
END) AS PaidRevenue
FROM dbo.Orders AS o
WHERE o.CreatedAtUtc >= @FromUtc
AND o.CreatedAtUtc < @ToUtc
GROUP BY CONVERT(date, o.CreatedAtUtc)
ORDER BY OrderDate;
The range predicate can seek on CreatedAtUtc; conversion happens only after candidate rows are found. A very large dashboard workload may still justify a daily summary table, especially when the same historical dates are recalculated repeatedly.
int.Next in Aggregation & Reporting: Duplicate Emails