Click here to Skip to main content
15,889,858 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there,

I am trying to get the lastest date per username. The data looks as follows:

Date Username Amount PID
12-12-2015 Mr Y R50 5997897
15-12-2015 Mr Y R56 8784545
13-07-2015 Ms J R89 87824
04-04-2015 Ms J R87 875414

So the output needs to be:
Date Username Amount PID
15-12-2015 Mr Y R56 8784545
13-07-2015 Ms J R89 87824

I have tried the following to no success:
SQL
select s1.Date, s1.UserName, s2.TradeAmount  from #ListOfTrans s1 
inner join
(
  select max(a.Date) as  Date,
    a.Amount, a.Username, a.PortfolioID
  from  #ListOfTrans a
  group by UserName,Amount,Date, PID
) s2
  on s1.UserName = s2.UserName
  and s1.Date = s2.Date
  and s1.PID = s2.PID
  group by s1.UserName, s2.Amount,s1.Date
Posted
Comments
Wombaticus 15-Jan-16 5:30am    
AM I missing something? WHat's wrong with
select Date, UserName, TradeAmount from ListOfTrans order by Date desc limit 2
?
Wombaticus 15-Jan-16 6:54am    
OK, sorry - me not reading the question properly... :(

Change your query like this and try again

SQL
select T.*
from    
(
  select a.UserName, max(a.Date) as  MAXDate
  from  #ListOfTrans a
  group by UserName
) T INNER JOIN #ListOfTrans LT ON T.UserName = LT.UserName AND T.Date = LT.MAXDATE
 
Share this answer
 
Comments
Maciej Los 15-Jan-16 15:12pm    
Looks perfect, +5!
SQL is great, cause there are tons of ways to write something. The one above will work, but I prefer the syntax below.

C#
SELECT (SELECT MAX(Date)
		FROM #ListOfTrans T2
		WHERE T2.UserName = T1.UserName) Date,
		UserName,
		Amount, 
		PID
FROM #ListOfTrans T1


One thing to note here, if this table is going to be large, this query could get slow. You should consider adding an index on the table of UserName and Date column.

Hogan
 
Share this answer
 
Comments
Maciej Los 15-Jan-16 15:16pm    
Looks promisingly... +4!
First thing first, use proper data type for the intended purpose of each table column, e.g. Date[^] instead of varchar for the date field, that will eliminate any data error and ugly conversion code.
Secondly, avoid using keywords or data type name such as 'date' as field name.
Then, try this:
C#
select * from tablename t1 where datefield = (
select max(datefield) from tablename t2 where t1.username=t2.username)
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900