Write a SELECT statement that answers this question:
What is the total quantity purchased for each product within each
category?Return these columns:
The category_name column from the category table
The product_name column from the products table
The total quantity purchased for each product with orders in the Order_Items table
Use the
WITH ROLLUP
operator to include rows that give a summary for
each category name as well as a row that gives the grand total.Use the
IF
andGROUPING
functions to replace null values in the
category_name
andproduct_name
columns with literal values if
they’re for summary rows.
select
categories.category_name
, products.product_name
, sum(order_items.quantity) as total_qty_purchased
from categories
inner join products on products.category_id = categories.category_id
inner join order_items on order_items.product_id = products.product_id
group by categories. category_name, product_name with rollup;
This returned null values. I’m expected to eliminate the null value rows using the if grouping function, but I don’t know how to do that.
2
Answers
You can eliminate the null values by having clause,
Use
IF
for the category name, since this is a two-way condition. It’s only null for the grand total.Use
CASE
for the product name because there are three possibilities: it will be null for the grand total or category subtotal, non-null for the product total. For the grand total you don’t need to put anything in the product name column of the result, because the category has already been replaced withGrand Total
.