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 |
naveenbalraj
Starting Member
18 Posts |
Posted - 2009-05-21 : 12:40:23
|
Hi All,I have this results joining 2 tables tbl1 and tbl2.date (tbl1) ID(tbl2) description(tbl2)1/4/2005 12 xx1/4/2005 13 yy4/6/2005 14 zz4/6/2005 14 aa4/6/2005 14 bb4/6/2005 14 cc4/6/2005 14 bb7/24/2006 15 dd2/27/2006 15 yy2/13/2006 15 aa11/30/2005 15 vv10/18/2005 15 rrSELECT tbl1.date ,tbl2.ID, tbl2.descriptionFROM tbl1 INNER JOINtbl2 ON tbl2.ID = tbl1.IDNow, I need only the rows with max date against each ID. The result I neededdate (tbl1) ID(tbl2) description(tbl2)1/4/2005 12 xx1/4/2005 13 yy4/6/2005 14 zz7/24/2006 15 ddAny help is greatly appreciated.-NB |
|
mualsh
Starting Member
8 Posts |
Posted - 2009-05-21 : 13:36:24
|
Do you want to share the table structures of tbl1 and tbl2 along with some sample data for these two tables? |
|
|
naveenbalraj
Starting Member
18 Posts |
Posted - 2009-05-21 : 16:54:25
|
tbl1id pk,intdatetbl2id1 pk,intid fkdescription table smaplestbl1 id date 12 1/4/200513 1/4/200514 4/6/200514 4/6/200514 4/6/200514 4/6/200514 4/6/200515 7/24/200615 2/27/200615 2/13/200615 11/30/200515 10/18/2005tbl2id1 id description1 12 xx2 13 yy3 14 zz4 14 aa5 14 bb6 14 cc7 14 bb8 15 dd9 15 yy10 15 aa11 15 vv12 15 rrdoes this help |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2009-05-21 : 18:12:43
|
[code]SELECT tbl1.date ,tbl2.ID, tbl2.descriptionFROM tbl1 INNER JOIN tbl2 ON tbl2.ID = tbl1.ID INNER JOIN ( SELECT date = max(tbl1.date) ,tbl2.ID FROM tbl1 INNER JOIN tbl2 ON tbl2.ID = tbl1.ID GROUP BY tbl2.ID ) m on tbl1.date = m.date AND tbl2.ID = m.ID[/code] KH[spoiler]Time is always against us[/spoiler] |
|
|
mualsh
Starting Member
8 Posts |
Posted - 2009-05-21 : 19:26:50
|
The whole idea of a primary key is to enable you to uniquely identify a row in a table. With that being said, I am not sure how your table tbl1 (with 'id' as its primary key) is letting you insert multiple rows (5 rows for id = 14). Can you please clarify? |
|
|
naveenbalraj
Starting Member
18 Posts |
Posted - 2009-05-22 : 14:40:17
|
thanks khtan. It helped.mualsh, please review his suggestion. |
|
|
|
|
|
|
|