I’ve got a very frustrating SQL issue which i can’t for the life of me solve with a derived query returning a composite key but also performing a MIN() aggregate function on another field within that table. If i was performing the MIN() on one of the composite keys it would be easy, but since i need to return both keys and perform the MIN() function as well to the outer query i can’t work out how to do this. The entire query looks like this:
SELECT
p.name as productname
,tmp.packageid
,tmp.price
,ppk2.packageoptionid
,ppk2.selcomproductid
FROM (
SELECT ppk.productid, ppk.packageid, MIN(ppk.price) as price
FROM product_package ppk
INNER JOIN package pk ON ppk.packageid = pk.id
INNER JOIN [plan] pl ON pk.planid = pl.id
WHERE pk.networkid = 1
GROUP BY ppk.productid, ppk.packageid
) tmp
INNER JOIN product_package ppk2 ON (
ppk2.productid = tmp.productid
AND ppk2.packageid = tmp.packageid
)
INNER JOIN product p ON (p.id = ppk2.productid)
WHERE p.isenabled = 1;
Current Results:
--------------------------------------
productid | packageid | price
1 500 0
1 501 19.95
1 502 29.95
2 501 0
3 500 15
3 504 39.95
Desired Results:
--------------------------------------
productid | packageid | price
1 500 0
2 501 0
3 500 15
The derived query “tmp” is where my issue lies as i need a unique rows back for each product/package combination with the lowest price, before joining onto the outer tables.
Any help would be greatly appreciated!
Well, I don’t know the data you actually have in your table. I just have the data your query returns. You didn’t answer to my comment asking for a sample of the data of your table and the DBMS you were using.
However, assuming the current data of your table is the one that comes out of your query, the following query will give you the “Desired Result” you’ve specified:
In table words, the query turns this:
Into this:
Let me know if it’s clear or not.