Database Basics
A sales table (store, amount) has seven rows: (A, 500), (A, 700), (B, 300), (B, 400), (C, 1200), (D, 200), (D, 900). How many rows does SELECT store, SUM(amount) FROM sales GROUP BY store HAVING SUM(amount) >= 1000 return?
- A1 row
- B3 rows
- C4 rows
Show answer and explanation
Answer: B. 3 rows
GROUP BY store gathers the rows by store into four groups with totals A = 500 + 700 = 1200, B = 300 + 400 = 700, C = 1200 and D = 200 + 900 = 1100. HAVING SUM(amount) >= 1000 keeps only groups whose total is 1000 or more, so the result has three rows: A, C and D. One row is the result of selecting by the amount of each individual row before grouping, as with WHERE amount >= 1000 (only C). Four rows is the number of groups without HAVING.
- A. This is the result of selecting individual rows with an amount of 1000 or more (filtering with WHERE).
- B. Correct. A (1200), C (1200) and D (1100) have totals of 1000 or more, giving three rows.
- C. This is the number of groups before HAVING filters them. B, with a total of 700, is removed.