Forum

Posted by Martin, Feb. 27, 2023, 10:01 a.m.

Q94 - what is the problem

I created a query for Q94 but I don't seem to get the answer, can someone please help? 

 

WITH a AS(
SELECT
product_id,
sum(unit_price_usd * qty) AS sales
FROM orders
WHERE 
   EXTRACT(YEAR FROM order_dt) = '2021'
  AND EXTRACT(MONTH FROM order_dt) = '08'
GROUP BY 1
ORDER by sales DESC
LIMIT 3
),
b AS(

SELECT
product_id,
sum(unit_price_usd * qty) AS sales
FROM orders
  WHERE 
  EXTRACT(YEAR FROM order_dt) = '2021'
  AND EXTRACT(MONTH FROM order_dt) = '08'
GROUP BY 1
ORDER by sales ASC
LIMIT 3
)
SELECT product_id, 'top' AS category FROM a 
UNION 
SELECT product_id, 'bottom' AS category FROM b
ORDER BY category
;

Answers

Hi Martin,

Which database are you using? Are you saying your query won't pass the online judge? Or do you need some further explnations of your code?

Your query looks correct.

And the first CTE grabs the top 3 product ranked by total sales, and later UNIONed together with the second CTE, which fetches the bottom 3 product.

Each order can contain multiple items, and each item can have different quantity, so we multiply unit_price_usd (unit price in us dollars) to qty (quantity) to get the product sales, then sum them up to find the total sales of the month.

 

Let me know if you have any other questions, keep up the good work!

Leon

Thanks for the quick response Leon! Very helpful. 

 

It does not pass the online judge. 

Martin, Feb. 27, 2023, 1:15 p.m.

You are welcome Martin!

Strange, which db are you using? Mind sharing your results?

I just ran on both postgres and mysql and it passed the  online judge for both engines.

 

 

Leon, Feb. 27, 2023, 1:21 p.m.
SQLPad user avatar

Leon (949)

Feb. 27, 2023, 10:31 a.m.