arcs / tasks /readable /017 /task_readable.md
yanlinf's picture
Release ARCS dataset
1fb4e2d verified
|
Raw History Blame Contribute Delete
1.32 kB

Task: 017

Database: retails

Question

Find the customer with the largest order value in each market segment.

Gold Query

WITH order_totals AS (
SELECT c_mktsegment, c.c_custkey, c.c_name, SUM(o.o_totalprice) AS total_o_totalprice
FROM customer c
JOIN orders o ON c.c_custkey = o.o_custkey
GROUP BY c_mktsegment, c.c_custkey, c.c_name
)
SELECT
ot.c_mktsegment AS market_segment,
ot.c_custkey AS customer_key,
ot.c_name AS customer_name,
ot.total_o_totalprice AS largest_value
FROM order_totals ot
JOIN (
SELECT ot2.c_mktsegment, MAX(ot2.total_o_totalprice) AS max_value
FROM order_totals ot2
GROUP BY ot2.c_mktsegment
) AS max_val ON ot.c_mktsegment = max_val.c_mktsegment AND ot.total_o_totalprice = max_val.max_value;

Execution Result:

market_segment customer_key customer_name largest_value
AUTOMOBILE 114308 Customer#000114308 5486668.8
BUILDING 58421 Customer#000058421 5487155.8
FURNITURE 41290 Customer#000041290 5473361.7
HOUSEHOLD 79933 Customer#000079933 5928489.4
MACHINERY 58387 Customer#000058387 5719569.4

5 rows