I have a large database of products. It has a one to many relationship to another table of prices. I can easily get, with one query, the MIN, MAX and AVG of a particular category.
SELECT
MIN(gbp.price) AS min,
ROUND(AVG(gbp.price),2) AS ave,
MAX(gbp.price) AS max
FROM sku AS s
INNER JOIN price gbp ON gbp.sid = s.id
However, I also want to be able to get the title of the product it relates to as well - I cannot get this resolved despite multiple searches and rewrites.
My data is similar to...
prod_id | title
===============
1 | prod1
2 | prod2
3 | prod3
4 | prod4
5 | prod5
6 | prod6
7 | prod7
price_id | prod_id | price | price_date
=======================================
1 | 1 | 2.99 | 2015/02/01
2 | 1 | 3.99 | 2015/02/12
3 | 2 | 12.99 | 2015/02/01
4 | 3 | 15.99 | 2015/02/01
5 | 4 | 29.99 | 2015/02/01
6 | 5 | 29.99 | 2015/02/01
7 | 5 | 24.99 | 2015/02/12
8 | 6 | 2.99 | 2015/02/01
9 | 7 | 99.99 | 2015/02/01
10 | 7 | 89.99 | 2015/02/12
I am going to presume that other people may want a query writing similar to this, so I am going to ask for two answers.
First one "simply" to return this...
min | min_title | ave | max | max_title
============================================
2.99 | prod1 | 31.39 | 99.99 | prod7
However, the real answer I want (despite the fact I cannot even solve the above) is where it gets even trickier.
The actual results I want is in the table below...
min | min_title | ave | max | max_title
============================================
2.99 | prod6 | 25.85 | 89.99 | prod7
The min is 2.99 for prod6 as the 2.99 price for prod1 has expired.
The max is 89.99 for prod7 as the 99.99 price for prod7 has expired.
The ave is 25.85 because of above and because the price for prod5 is 24.99.
I am not expecting answers for everything, just answering the first question (in bold) will likely lead me to the answer for the second part (as I have similar queries that get the latest price etc).