Link to home
Start Free TrialLog in
Avatar of Geoff Sutton
Geoff SuttonFlag for Canada

asked on

Help with an SQL Query

I have 2 tables, Codes and Targets.  They have a common key, Code.  I am trying to put together a simple query to put the targets identity into Codes as a foreign key.

This is using SQL Server 2008.

Select Code, Target from Codes as C
Select Top 1 id, Code from Targets as T where T.Code=C.Code Order By T.FromDate Desc

Those are the 2 queries that I need to join to get something along the lines of
Update Codes set Target=(SELECT TOP 1 T.ID From Targets as T WHERE T.Code=Codes.Code ORDER BY T.FromDate DESC)

How can I properly form this query?
Avatar of awking00
awking00
Flag of United States of America image

Can you provide the relevant table structures with some sample data and the expected result?
something like this:
UPDATE CODES
SET    Target = ID
FROM   Codes c INNER JOIN Targets t
      ON c.Code = t.Code

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Aneesh
Aneesh
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Geoff Sutton

ASKER

Thanks.  I knew it was a relatively simple query, just couldn't put the pieces together.  It was quick and did exactly what I needed.
Select Code, Target
from Codes as C, (Select Top 1 id, Code from Targets Order By T.FromDate Desc
 )  t
where T.Code=C.Code