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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Get only one row on cross-table query

Author  Topic 

mattt
Posting Yak Master

194 Posts

Posted - 2008-02-05 : 08:42:02
Hi,

In my data structure I have two related tables - Advertising and AdvertisingNotes. One Advert in Advertising may have multiple records in AdvertisingNotes.

What I want to do is a cross-table select (easy enough it itself) between Advertising and AdvertisingNotes which returns only one row per advert and this row must contain the most recent (highest date) matching record from AdvertisingNotes.

Is this possible?

Cheers,
Matt

jackv
Master Smack Fu Yak Hacker

2179 Posts

Posted - 2008-02-06 : 10:49:06
Yes , you could do something like, :
SELECT myCols
FROM Advertising as a
INNER JOIN (SELECT TOP 1 myCols FROM AdvertisingNotes as an WHERE a.ID = an.ID ORDER by myDate DESC) an2
ON a.ID = an2.ID

Jack Vamvas
--------------------
Search IT jobs from multiple sources- http://www.ITjobfeed.com
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-02-06 : 10:53:26
SELECT t.ID,t.myCols
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY a.ID ORDER BY an.NotesID DESC) AS RowNo,
a.ID,
an.myCols
FROM Advertising as a
INNER JOIN AdvertisingNotes as an
ON a.ID = an.ID )t
WHERE t.RowNo=1
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-02-06 : 10:54:13
Asked answered here
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=96876



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page
   

- Advertisement -