0% found this document useful (0 votes)
4 views6 pages

GROUPBY1

Uploaded by

krishnakantuu007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views6 pages

GROUPBY1

Uploaded by

krishnakantuu007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

CASE & WHEN

Find out which vendors primarily sell fresh products and which don’t. Add an
identifier column for the same.

SELECT Alternate: Using IF()

vendor_id,
SELECT
vendor_name,
vendor_id,
vendor_type,
vendor_name,
CASE vendor_type,
WHEN lower(vendor_type) LIKE "%fresh%" IF(UPPER(vendor_type) LIKE "%FRESH%",

THEN 1 "Fresh", "Not Fresh") AS is_fresh


FROM `farmers_market.vendor`;
ELSE 0
END AS is_fresh
FROM `farmers_market.vendor`
Put the total cost to customer purchases into bins of:
- Under $5.00
- 5 - 9.99
- 10 - 19.99
- 20 and over
SELECT
customer_id,
market_date,
quantity * cost_to_customer_per_qty AS total_amt,
CASE
WHEN quantity * cost_to_customer_per_qty < 5
THEN "Under $5"
WHEN quantity * cost_to_customer_per_qty BETWEEN 5 AND 9.99
THEN "$5 - $9.99"
WHEN quantity * cost_to_customer_per_qty BETWEEN 10 AND 19.99
THEN "$10 - $19.99"
ELSE "$20 and over"
END AS price_bins
FROM `farmers_market.customer_purchases`
Count the number of purchases each customer made per market date.

SELECT
customer_id,
market_date,
COUNT(*) AS num_orders
FROM `farmers_market.customer_purchases`
GROUP BY customer_id, market_date
ORDER BY market_date, customer_id
Calculate the total quantity purchased by each customer per market_date.

SELECT
customer_id,
market_date,
SUM(quantity) AS total_quantity
FROM `farmers_market.customer_purchases`
GROUP BY customer_id, market_date
ORDER BY market_date, customer_id
How many different kinds of products were purchased by each customer on each
market date?

SELECT
customer_id,
market_date,
COUNT(DISTINCT product_id) num_products
FROM `farmers_market.customer_purchases`
GROUP BY customer_id, market_date
ORDER BY market_date, customer_id

You might also like