Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select info from table where row has max date

My table looks something like this:

group    date      cash  checks   1    1/1/2013     0      0   2    1/1/2013     0      800   1    1/3/2013     0      700   3    1/1/2013     0      600   1    1/2/2013     0      400   3    1/5/2013     0      200 

-- Do not need cash just demonstrating that table has more information in it

I want to get the each unique group where date is max and checks is greater than 0. So the return would look something like:

group    date     checks   2    1/1/2013    800   1    1/3/2013    700   3    1/5/2013    200 

attempted code:

SELECT group,MAX(date),checks     FROM table     WHERE checks>0     GROUP BY group     ORDER BY group DESC 

problem with that though is it gives me all the dates and checks rather than just the max date row.

using ms sql server 2005

like image 961
kqlambert Avatar asked Oct 17 '13 17:10

kqlambert


People also ask

How do you select a row with max date?

Select row with max date per user using MAX() function Another way to get the latest record per user is using inner queries and Max() function. Max() function, when applied on a column, gives the maximum value of that column.

How do I find the maximum date in a table in SQL?

MAX() function will give you the maximum values from all the values in a column. MAX function works with “date” data types as well and it will return the maximum or the latest date from the table.

How do I select the rows with the most recent date in SQL?

Here is the syntax that we can use to get the latest date records in SQL Server. Select column_name, .. From table_name Order By date_column Desc; Now, let's use the given syntax to select the last 10 records from our sample table.


1 Answers

SELECT group,MAX(date) as max_date FROM table WHERE checks>0 GROUP BY group 

That works to get the max date..join it back to your data to get the other columns:

Select group,max_date,checks from table t inner join  (SELECT group,MAX(date) as max_date FROM table WHERE checks>0 GROUP BY group)a on a.group = t.group and a.max_date = date 

Inner join functions as the filter to get the max record only.

FYI, your column names are horrid, don't use reserved words for columns (group, date, table).

like image 149
Twelfth Avatar answered Sep 23 '22 04:09

Twelfth