Conditional Sum Aggregation with Group Filtering
SQL & DataAuto-graded · 18 test casesLast updated
Compute filtered totals two ways and group-then-threshold results, mirroring SQL conditional aggregation semantics.
You are given a list of transaction records. Each record is a dictionary with three keys:
"group"— a string identifying the group (e.g. a merchant or region)."amount"— an integer representing the transaction value."qualifies"— a boolean indicating whether this transaction should be counted toward the conditional total.
You are also given an integer minimum_group_total.
Your function must return a dictionary with exactly three keys:
"where_total"— the sum ofamountover every record whosequalifiesisTrue. This mirrors a SQL query that filters rows with aWHEREclause before aggregating."case_total"— the sum ofamountfor every record, treatingamountas0whenqualifiesisFalse. This mirrorsSUM(CASE WHEN qualifies THEN amount ELSE 0 END)applied to all rows without aWHEREfilter. Both totals will be numerically equal, but the approaches differ conceptually."groups"— a dictionary mapping each distinct group name to the sum ofamountvalues from that group's qualifying records only. Groups with no qualifying records must still appear with a value of0. After computing the per-group totals, keep only the groups whose total is greater than or equal tominimum_group_total. This mirrors a SQLGROUP BYfollowed by aHAVINGclause on the conditional aggregate.
Return the dictionary with keys "where_total", "case_total", and "groups".
Constraints
0 <= len(rows) <= 10^5- Each record always contains all three keys:
"group","amount", and"qualifies". amountis an integer in the range[-10^6, 10^6].qualifiesis a boolean (TrueorFalse)."group"is a non-empty string.minimum_group_totalis an integer in the range[-10^9, 10^9].- An empty input list yields
0for both totals and an empty dictionary for"groups". - Groups whose qualifying total is less than
minimum_group_totalare excluded from"groups". Groups that never appear in the input do not appear in"groups". - The order of keys in the returned dictionaries does not matter.
Examples
Example 1
Input: conditional_aggregation([{'group': 'A', 'amount': 100, 'qualifies': True}, {'group': 'A', 'amount': 40, 'qualifies': False}, {'group': 'B', 'amount': 75, 'qualifies': True}], 50)
Output: {'where_total': 175, 'case_total': 175, 'groups': {'A': 100, 'B': 75}}
Example 2
Input: conditional_aggregation([{'group': 'north', 'amount': 10, 'qualifies': True}, {'group': 'north', 'amount': 20, 'qualifies': True}, {'group': 'south', 'amount': 100, 'qualifies': False}], 25)
Output: {'where_total': 30, 'case_total': 30, 'groups': {'north': 30}}
Example 3
Input: conditional_aggregation([{'group': 'A', 'amount': 5, 'qualifies': False}, {'group': 'B', 'amount': 8, 'qualifies': False}], 0)
Output: {'where_total': 0, 'case_total': 0, 'groups': {'A': 0, 'B': 0}}
Hints
Hint 1
Both the WHERE-style and CASE-WHEN-style totals produce the same number; the difference only becomes visible when grouping, because WHERE drops groups with no qualifying rows while CASE WHEN retains them with a zero total.
Hint 2
Initialize every group's running total to 0 before iterating over its records, so groups whose records never qualify still appear in the output with a value of 0.
Hint 3
Apply the minimum threshold only after all records have been processed, analogous to HAVING running after GROUP BY in SQL's logical execution order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
The problem asks us to simulate two SQL aggregation strategies in Python and then group-and-filter the results.
WHERE-style total: Iterate over all records and add amount to a running sum only when qualifies is True. Rows that do not qualify are skipped entirely, exactly like a WHERE clause removes rows before aggregation.
CASE WHEN-style total: Iterate over all records, but every row contributes something. Qualifying rows contribute their amount; non-qualifying rows contribute 0. This mirrors SUM(CASE WHEN qualifies THEN amount ELSE 0 END). The numeric result is identical to the WHERE-style total because adding zeros does not change a sum, but the semantic difference matters once grouping is introduced.
Per-group totals with HAVING filter: Build a dictionary keyed by group name. Every group is initialized to 0 before any records are added, so groups whose records never qualify still appear with a total of 0 rather than being silently absent — this is the critical behavioral difference between WHERE and CASE WHEN in grouped queries. As we iterate, we add amount to the group's running total only for qualifying records. After all records are processed, we keep only the groups whose total meets or exceeds minimum_group_total, mirroring HAVING filtering groups after GROUP BY has formed them.
Why the two totals are always equal: Σ amount over qualifying rows equals Σ (amount if qualifies else 0) over all rows, because non-qualifying rows contribute exactly 0 in the second sum and nothing in the first — both are the same value.
Edge cases handled:
- Empty input: both totals are
0(Python'ssumover an empty iterable returns0), and"groups"is an empty dictionary. - Groups with only non-qualifying records: they appear with a total of
0and are retained only if0 >= minimum_group_total. - Negative amounts: summed as-is; a group total can go negative and may fall below the threshold.
minimum_group_total <= 0: groups with a total of0are retained, so all groups from the input will appear.
Time complexity: O(n), where n is the number of records. Each record is visited a constant number of times.
Space complexity: O(g), where g is the number of distinct groups, for storing the group totals dictionary.
from typing import Dict, List
def conditional_aggregation(rows: List[Dict[str, object]], minimum_group_total: int) -> Dict[str, object]:
# WHERE-style: sum only qualifying rows
where_total = sum(row["amount"] for row in rows if row["qualifies"])
# CASE WHEN-style: every row contributes, non-qualifying rows contribute 0
case_total = sum(row["amount"] if row["qualifies"] else 0 for row in rows)
# GROUP BY group_name with SUM(CASE WHEN qualifies THEN amount ELSE 0 END):
# initialize every group to 0 so groups with no qualifying rows are retained.
group_totals: Dict[str, int] = {}
for row in rows:
name = row["group"]
if name not in group_totals:
group_totals[name] = 0
if row["qualifies"]:
group_totals[name] += row["amount"]
# HAVING SUM(...) >= minimum_group_total
groups = {
name: total
for name, total in group_totals.items()
if total >= minimum_group_total
}
return {
"where_total": where_total,
"case_total": case_total,
"groups": groups,
}