CODE WORKSPACE

Line items per order

Return o.order_id and line_items (the count of matching order_items rows) for every order that has at least one line item. Order by order_id.

JOIN order_items ON oi.order_id = o.order_id, GROUP BY o.order_id, COUNT(*) AS line_items.

Sample input

ordersOrders (order_id shown). Orders with no items are excluded by the INNER JOIN.
order_id
1001
1002
1003
1004
order_itemsItem lines; order_id repeats once per line item (15 rows in the sandbox).
order_idsku
1001SKU-A
1001SKU-B
1001SKU-C
1002SKU-C
1002SKU-D
1004SKU-A

Expected output

Expected outputOne row per order that has items, with its line-item count. 7 of the 12 orders have items.
order_idline_items
10013
10022
10043
10052
10071
10082
10102

Constraints

JOIN orders to order_items on order_id (an INNER JOIN, so orders with no items are excluded). GROUP BY o.order_id and COUNT(*) the line items, aliased as line_items.

Expected skills

Joining to a finer-grain table and aggregating back to one row per order with GROUP BY.

SQL
Loading...

AI evaluation

Run the SQL query to inspect preview rows.