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
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With