Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use SQL group to filter rows with maximum date value

I have the following table

CREATE TABLE Test
    (`Id` int, `value` varchar(20), `adate` varchar(20))
;

INSERT INTO Test
    (`Id`, `value`, `adate`)
VALUES
    (1, 100, '2014-01-01'),
    (1, 200, '2014-01-02'),
    (1, 300, '2014-01-03'),
    (2, 200, '2014-01-01'),
    (2, 400, '2014-01-02'),
    (2, 30 , '2014-01-04'),
    (3, 800, '2014-01-01'),
    (3, 300, '2014-01-02'),
    (3, 60 , '2014-01-04')
;

I want to achieve the result which selects only Id having max value of date. ie

Id ,value ,adate

 1, 300,'2014-01-03'     
 2, 30 ,'2014-01-04'     
 3, 60 ,'2014-01-04'

how can I achieve this using group by? I have done as follows but it is not working.

Select Id,value,adate
from Test
group by Id,value,adate
having adate = MAX(adate)

Can someone help with the query?

like image 583
NewtonCode Avatar asked Jun 10 '14 11:06

NewtonCode


People also ask

How to use SQL max function on date type of table?

In this part, you will see the usage of SQL MAX() function on date type of the column of a table. Example: Sample table: orders. To get the maximum 'ord_date' from the 'orders' table, the following SQL statement can be used : SELECT MAX (ord_date) AS "Max Date" FROM orders;

How to get the Max date of an agent in SQL?

SQL MAX () on date with group by To get data of 'agent_code' and maximum 'ord_date' with an user defined column alias 'Max Date' for each agent from the orders table with the following condition - 1. 'agent_code' should come in a group the following SQL statement can be used :

How to find the maximum value of a column over each group?

In this page we are discussing, how the GROUP BY clause along with the SQL MAX() can be used to find the maximum value of a column over each group. Example: Sample table: agents. To get data of 'working_area' and maximum 'commission' for the agents of each 'working_area' from the 'agents' table with the following condition -.

What is the difference between aggregate and filter in SQL?

GROUP BY enables you to use aggregate functions on groups of data returned from a query. FILTER is a modifier used on an aggregate function to limit the values used in an aggregation. All the columns in the select statement that aren’t aggregated should be specified in a GROUP BY clause in the query.


2 Answers

Please try:

select 
  * 
from 
  tbl a
where 
  a.adate=(select MAX(adate) from tbl b where b.Id=a.Id)
like image 158
TechDo Avatar answered Oct 05 '22 02:10

TechDo


Select the maximum dates for each id.

select id, max(adate) max_date
from test
group by id

Join on that to get the rest of the columns.

select t1.*
from test t1
inner join (select id, max(adate) max_date
            from test
            group by id) t2
on t1.id = t2.id and t1.adate = t2.max_date;
like image 26
Mike Sherrill 'Cat Recall' Avatar answered Oct 05 '22 03:10

Mike Sherrill 'Cat Recall'