SQL Query with conditional JOIN

Posted by mariki on Stack Overflow See other posts from Stack Overflow or by mariki
Published on 2010-04-13T14:13:13Z Indexed on 2010/04/13 14:22 UTC
Read the original article Hit count: 265

Filed under:
|

The scenario:

Table1
CatId|Name|Description

Table2
ItId|Title|Date|CatId (foreign key)

I want to return all rows from Table1 and Title,Date from Table2, where The returned from Table 2 must be the Latest one by the date column. (in second table there many items with same CatId and I need just the latest)

I have 2 queries but can't merge them together:

Query 1:  
SELECT Table1.Name,  Table1.Description,
       Table2.Title, Table2.Date
FROM 
       Table1 LEFT JOIN Table2 ON Table1.CatId=Table2.CatId

Query2:

SELECT TOP 1 Table2.Title, Table2.Date
FROM 
    Table2
WHERE 
    Table2.CatId = @inputParam
ORDER BY Table2.Date DESC

© Stack Overflow or respective owner

Related posts about sql

Related posts about sql-server-2005