Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rows with max date when grouping in MySQL?

Tags:

sql

mysql

max

I have a table with prices and dates on product:

id
product
price
date

I create a new record when price change. And I have a table like this:

id product price date
1  1       10    2014-01-01
2  1       20    2014-02-17
3  1        5    2014-03-28
4  2       25    2014-01-05
5  2       12    2014-02-08
6  2       30    2014-03-12

I want to get last price for all products. But when I group with "product", I can't get a price from a row with maximum date.

I can use MAX(), MIN() or COUNT() function in request, but I need a result based on other value.

I want something like this in final:

product price date
1        5    2014-03-28
2       30    2014-03-12

But I don't know how. May be like this:

SELECT product, {price with max date}, {max date}
FROM table
GROUP BY product
like image 237
MaxKu Avatar asked Jun 16 '14 10:06

MaxKu


People also ask

Can you use Max in GROUP BY?

SQL Server MAX() with GROUP BY clause example First, the GROUP BY clause divided the products into groups by the brand names. Then, the MAX() function is applied to each group to return the highest list price for each brand.

Can we use max with GROUP BY in SQL?

MySQL MAX() function with GROUP BY retrieves maximum value of an expression which has undergone a grouping operation (usually based upon one column or a list of comma-separated columns).

Can I use Max on date in SQL?

MAX function works with “date” data types as well and it will return the maximum or the latest date from the table.

Can we use Max in Where clause in MySQL?

MySQL MAX() Function with WHERE ClauseThe WHERE clause allows us to filter the result from the selected records. The following statement finds the maximum income in all rows from the employee table. The WHERE clause specifies all those rows whose emp_age column is greater than 35.


2 Answers

Alternatively, you can have subquery to get the latest get for every product and join the result on the table itself to get the other columns.

SELECT  a.*
FROM    tableName a
        INNER JOIN 
        (
            SELECT  product, MAX(date) mxdate
            FROM    tableName
            GROUP   BY product
        ) b ON a.product = b.product
                AND a.date = b.mxdate
like image 65
John Woo Avatar answered Oct 11 '22 10:10

John Woo


You can use a subquery that groups by product and return the maximum date for every product, and join this subquery back to the products table:

SELECT
  p.product,
  p.price,
  p.date
FROM
  products p INNER JOIN (
    SELECT
      product,
      MAX(date) AS max_date
    FROM
      products
    GROUP BY
      product) m
  ON p.product = m.product AND p.date = m.max_date
like image 33
fthiella Avatar answered Oct 11 '22 10:10

fthiella