Bird
0
0

Which query correctly uses GROUPING SETS to achieve this?

hard📝 Application Q8 of 15
PostgreSQL - Aggregate Functions and GROUP BY
You want to generate a report showing total sales by city, by product, and by city-product combination from a sales(city, product, amount) table. Which query correctly uses GROUPING SETS to achieve this?
ASELECT city, product, SUM(amount) FROM sales GROUP BY GROUPING SETS ((city), (product), (city, product));
BSELECT city, product, SUM(amount) FROM sales GROUP BY city, product;
CSELECT city, product, SUM(amount) FROM sales GROUP BY ROLLUP(city, product);
DSELECT city, product, SUM(amount) FROM sales GROUP BY CUBE(city, product);
Step-by-Step Solution
Solution:
  1. Step 1: Identify required groupings

    We need totals by city, by product, and by city-product pairs separately.
  2. Step 2: Match with GROUPING SETS syntax

    SELECT city, product, SUM(amount) FROM sales GROUP BY GROUPING SETS ((city), (product), (city, product)); explicitly lists these three grouping sets correctly.
  3. Final Answer:

    SELECT city, product, SUM(amount) FROM sales GROUP BY GROUPING SETS ((city), (product), (city, product)); -> Option A
  4. Quick Check:

    GROUPING SETS explicitly lists needed groupings [OK]
Quick Trick: Use GROUPING SETS to list exact groupings needed [OK]
Common Mistakes:
  • Using GROUP BY without GROUPING SETS for multiple groupings
  • Confusing ROLLUP or CUBE with exact grouping sets
  • Missing parentheses in GROUPING SETS

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes