| Author |
Topic |
|
rebelman
Starting Member
4 Posts |
Posted - 2007-08-14 : 14:50:56
|
| Hi all, I am relatively new to sql and have an issue I am trying to solve. I have a table with several records with the same id:id amount date-- ------ ------1 100 01/01/20061 2000 06/01/20052 200 01/01/20052 500 06/01/2007how would I get the data for the record with the newest date?So I would return:id amount date-- ------ ----------1 100 01/01/20062 500 06/01/2007Thanks in advance for the help. |
|
|
ashley.sql
Constraint Violating Yak Guru
299 Posts |
Posted - 2007-08-14 : 14:59:09
|
| select id, amount, max(date)from table group by id, amountAshley Rhodes |
 |
|
|
ashley.sql
Constraint Violating Yak Guru
299 Posts |
Posted - 2007-08-14 : 15:03:09
|
| what about the amount, is the amount goiing to be different for 2 different dates.my query will work only if the amount is also same. let me if you posted the data randomly and the amount is suppose to be same, if not my query is not correctAshley Rhodes |
 |
|
|
rebelman
Starting Member
4 Posts |
Posted - 2007-08-14 : 15:03:43
|
| I tried that and that seems to return all of the records, not just one of each group of id's.ThanksMike |
 |
|
|
rebelman
Starting Member
4 Posts |
Posted - 2007-08-14 : 15:04:36
|
| The amounts are also random and different.Thanks |
 |
|
|
dinakar
Master Smack Fu Yak Hacker
2507 Posts |
Posted - 2007-08-14 : 15:06:19
|
| [code]Declare @T Table (id int, amount decimal(10,2), date datetime)insert into @tselect 1, 100 ,'01/01/2006' union allselect 1, 2000, '06/01/2005' union allselect 2, 200, '01/01/2005' union allselect 2, 500 ,'06/01/2007'select T.*from @t TJOIN ( SELECT Id, MAX(Date) AS MDate FROM @T T2 GROUP BY ID ) T1 ON T.Id= T1.Id AND T.Date = T1.MDate[/code]Dinakar Nethi************************Life is short. Enjoy it.************************http://weblogs.sqlteam.com/dinakar/ |
 |
|
|
ashley.sql
Constraint Violating Yak Guru
299 Posts |
Posted - 2007-08-14 : 15:09:49
|
| THIS WILL WORK FINE FOR YOUR SCENARIO IF AMOUNT IS NOT SAMEcreate table t111 (id int, amount int, date datetime)insert into t111 values(1, 100, '01/01/2006')insert into t111 values(1, 2000, '06/01/2005')insert into t111 values(2, 200, '01/01/2005')insert into t111 values(2, 500, '06/01/2007')select A.id, A.Date, B.amountfrom(select id, max(date) Date from t111group by id) Ainner join(select amount, max(date)date from t111 group by amount ) Bon A.date = B.dateAshley Rhodes |
 |
|
|
rebelman
Starting Member
4 Posts |
Posted - 2007-08-14 : 15:21:28
|
| Thank you for the replies, they were very helpfull and solved my problem. |
 |
|
|
ashley.sql
Constraint Violating Yak Guru
299 Posts |
Posted - 2007-08-14 : 16:49:03
|
| which one was fasterAshley Rhodes |
 |
|
|
|