I’m building a stored procedure that returns the lowest price of each product and show their respective store info and date. This SP should allow optional parameters for StoreCity
and ProdType
. I’m a bit stuck on the SELECT
query.
These are the tables:
+-----------+
| Product |
+-----------+
| id_prod |
| prod_type |
+-----------+
+-----------+
| Store |
+-----------+
| idStore |
| StoreName |
| StoreCity |
+-----------+
+---------------+
| Product_Store |
+---------------+
| fkStore |
| fkProd |
| PriceProd |
| PriceDate |
+---------------+
At first, I was trying this:
SELECT fkProd, MIN(PriceProd)
FROM Product_Store
GROUP BY fkProd;
to get this:
+---------+---------------+
| fkProd | MIN(PriceProd)|
+---------+---------------+
| 1 | 1.11 |
| 2 | 0.11 |
| 3 | 1.11 |
| 4 | 0.11 |
+---------+---------------+
It’s close to what I expected, but I also need the fkStore
and PriceDate
. So I use the query below, but (as far as I can see) it won’t allow me to use parameters (they should be in the first SELECT
within the WITH
clause, right?)
WITH q AS (
SELECT
fkStore,
fkProd,
PriceProd, row_number() over (partition by fkProd order by PriceProd ASC) MinPrice,
PriceDate
FROM Product_Store)
SELECT
Store.StoreName,
Product.ProdType,
PriceProd,
PriceDate
FROM q
INNER JOIN Store ON q.fkStore = Store.idStore
INNER JOIN Product ON q.fkProd = Product.idProd
WHERE MinPrice = 1
3
Answers
This should work:
If you are looking for a stored procedure-based answer below would do.
Refer the below SQL code:
In order to get your desired result with optional parameters you can create an SP like:
Call SP like:
Or
and get underlying results:
| id_prod | prod_type | StoreName | StoreCity | PriceProd | PriceDate |
| ——- | ———– | ——— | ——— | ——— | ———- |
| 1 | Electronics | BestBuy | New York | 279.99 | 2024-02-01 |
| 2 | Groceries | Target | Chicago | 13.99 | 2024-01-01 |
| 3 | Clothing | Target | Chicago | 44.99 | 2024-01-01 |
Hope this is what you needed