There is a table tbl_products
that contains data as shown below:
Id Name
----------
1 P1
2 P2
3 P3
4 P4
5 P5
6 P6
And another table tbl_inputs
that contains data as shown below:
Id Product_Id Price Register_Date
----------------------------------------
1 1 10 2010-01-01
2 1 20 2010-10-11
3 1 30 2011-01-01
4 2 100 2010-01-01
5 2 200 2009-01-01
6 3 500 2011-01-01
7 3 270 2010-10-15
8 4 80 2010-01-01
9 4 50 2010-02-02
10 4 92 2011-01-01
I want to select all products(id, name, price, register_date) with maximum date in each group.
For Example:
Id Name Price Register_Date
----------------------------------------
3 P1 30 2011-01-01
4 P2 100 2010-01-01
6 P3 500 2011-01-01
10 P4 92 2011-01-01
Something like this..
you can use the max function and the group by clause. if you only need results from the table tbl_inputs you even don't need a join select product_id, max(register_date), price from tbl_inputs group by product_id, price
if you need field from the tbl_prducts you have to use a join.
Try this:
This is, of course, assuming your dates are unique. if they are not, you need to add the DISTINCT Keyword to the outer SELECT statement.
edit
Sorry, I didn't explain it very well. Your dates can be duplicated, it's not a problem as long as they are unique per product id. if you can have duplicated dates per product id, then you will have more then one row per product in the outcome of the select statement I suggested, and you will have to find a way to reduce it to one row per product. i.e: If you have records like that (when the last date for a product appears more then once in your table with different prices)
it will result in having both of these records as outcome. However, if the register_date is unique per product id, then you will get only one result for each product id.
Although is not the optimum way you can do it like:
But as I said earlier .. this is not the way to go in this case.