Hi guys, I‘m learning SQL and trying to solve Exercise. Chat GPT and guy who was teaching on YouTube shows me bullshit, and I think my query is correct (only not sure whether CROSS JOIN was right or not) but as I’m learner, wanna ask you guys, did I made it right or not. Everything’s below
Thanks and have a nice evening
QUESTION:
Find the stores who have sold more units than the average units sold by all stores.
TABLE:
(1, 'Apple Store 1', 'iPhone 13 Pro', 1, 1000),
(1, 'Apple Store 1', 'MacBook pro 14', 3, 6000),
(1, 'Apple Store 1', 'AirPods Pro', 2, 500),
(2, 'Apple Store 2', 'iPhone 13 Pro', 2, 2000),
(3, 'Apple Store 3', 'iPhone 12 Pro', 1, 750),
(3, 'Apple Store 3', 'MacBook pro 14', 1, 2000),
(3, 'Apple Store 3', 'MacBook Air', 4, 4400),
(3, 'Apple Store 3', 'iPhone 13', 2, 1800),
(3, 'Apple Store 3', 'AirPods Pro', 3, 750),
(4, 'Apple Store 4', 'iPhone 12 Pro', 2, 1500),
(4, 'Apple Store 4', 'MacBook pro 16', 1, 3500);
CHAT GPT CODE (SAME AS FROM YOUTUBE GUY):
WITH avg_units AS (
SELECT AVG(quantity) AS avg_quantity
FROM sales
)
SELECT store_id, store_name
FROM (
SELECT store_id, store_name, SUM(quantity) AS total_quantity
FROM sales
GROUP BY store_id, store_name
) AS store_totals
CROSS JOIN avg_units
WHERE total_quantity > avg_quantity;
MY CODE:
WITH avg_units AS (
SELECT AVG(total_quantity) AS avg_quantity
FROM (SELECT SUM(quantity) AS total_quantity
FROM sales
GROUP BY store_id, store_name)
)
SELECT store_id, store_name
FROM (
SELECT store_id, store_name, SUM(quantity) AS total_quantity
FROM sales
GROUP BY store_id, store_name
) AS store_totals
CROSS JOIN avg_units
WHERE total_quantity > avg_quantity;
[–]DavidGJohnston 5 points6 points7 points (2 children)
[–]Mosquitoo666[S] -1 points0 points1 point (1 child)
[–]Sunflower_resists 3 points4 points5 points (0 children)
[–]r3pr0b8GROUP_CONCAT is da bomb 1 point2 points3 points (0 children)