Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
rookie_sql
Constraint Violating Yak Guru
443 Posts |
Posted - 2008-12-11 : 09:50:35
|
| Hi i need to get the top record for max date by Code ExampleCode Date Amt A 2008-12-11 1000A 2008-12-12 1100A 2008-12-12 1100A 2008-12-12 1100B 2008-12-11 1100B 2008-12-12 1100B 2008-12-13 1100B 2008-12-14 1300A 2008-12-11 1100C 2008-12-12 1100C 2008-12-13 1100C 2008-12-14 1200 Expected Result set will be Code Date Amt A 2008-12-12 1100B 2008-12-14 1300C 2008-12-14 1200 |
|
|
sodeep
Master Smack Fu Yak Hacker
7174 Posts |
Posted - 2008-12-11 : 09:53:32
|
| select Code,max(date)as maxdate,max(amt) as maxamtfrom tablegroup by Code |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-12-11 : 09:54:52
|
| [code]SELECT Code,Date,AmtFROM (SELECT ROW_NUMBER() OVER (PARTITION BY Code ORDER BY Date DESC) AS Seq,*FROM TABLE)tWHERE Seq=1[/code] |
 |
|
|
sakets_2000
Master Smack Fu Yak Hacker
1472 Posts |
Posted - 2008-12-11 : 09:59:46
|
quote: Originally posted by sodeep select Code,max(date)as maxdate,max(amt) as maxamtfrom tablegroup by Code
This would give wrong result. Try this,select a.code,a.maxdate,b.amtfrom (select Code,max([Date]) as maxdate from yourtable group by Code )ajoin yourtable b on a.code=b.code and a.maxdate=b.[Date] |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-12-11 : 10:02:13
|
quote: Originally posted by sodeep select Code,max(date)as maxdate,max(amt) as maxamtfrom tablegroup by Code
the max values will not necessarily from same record which is not what OP wants. he wants details associated with recent record so it should be like thisselect t1.*from table t1join(select Code,max(date)as maxdatefrom tablegroup by Code)t2on t2.maxdate=t1.dateand t2.Code=t1.Code |
 |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2008-12-12 : 00:25:53
|
quote: Originally posted by sakets_2000
quote: Originally posted by sodeep select Code,max(date)as maxdate,max(amt) as maxamtfrom tablegroup by Code
This would give wrong result. Try this,select a.code,a.maxdate,b.amtfrom (select Code,max([Date]) as maxdate from yourtable group by Code )ajoin yourtable b on a.code=b.code and a.maxdate=b.[Date]
Duplicate records are coming so use distinct keyword select distinct t.code,t.date ,tp.amtfrom (select code, max(date) as date from #temp group by code) t left join #temp tp on t.date = tp.date and t.code = tp.code |
 |
|
|
|
|
|
|
|