带有条件JOIN的SQL查询

时间:2010-04-13 14:13:14

标签: sql sql-server-2005

情景:

表1
CATID |名称|说明

表2
ItId |标题|日期| CatId(外键)

我想返回表1中的所有行和表2中的标题,日期,其中 表2中返回的内容必须是日期列中的最新值。 (在第二个表中有许多具有相同CatId的项目,我只需要最新的)

我有2个查询,但无法将它们合并在一起:

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

3 个答案:

答案 0 :(得分:2)

您可以使用UNION,但是您需要使列匹配:

好的,在重读了这个问题后,我明白了你要做的事情。

这应该可以解决问题:

SELECT Table1.Name,  Table1.Description,
 T2.Title, T2.Date

FROM
 Table1

LEFT JOIN (
 SELECT CatId, Title, Date, ROW_NUMBER() over (ORDER BY CatId, Date DESC) - RANK() over (ORDER BY CatID) as Num

 FROM  Table2) T2 on T2.CatId = Table1.CatId AND T2.Num = 0

答案 1 :(得分:0)

不应该这样吗?

SELECT Table1.Name,  Table1.Description,
   T2.Title, T2.Date
FROM 
   Table1 LEFT JOIN (

SELECT TOP 1 Table2.CatId Table2.Title, Table2.Date
FROM 
Table2
WHERE 
Table2.CatId = Table1.catId 
ORDER BY Table2.Date DESC

) T2 
ON Table1.CatId=T2.CatId

答案 2 :(得分:0)

听起来你在谈论分组最大值(Table2中每个匹配行的最新行Table1),在这种情况下,最简单的方法是使用ROW_NUMBER:< / p>

WITH CTE AS
(
    SELECT
        t1.Name, t1.Description, t2.Title, t2.Date,
        ROW_NUMBER() OVER (PARTITION BY t1.CatId ORDER BY t2.Date DESC) AS Seq
    FROM Table1 t1
    LEFT JOIN Table2 t2
        ON t2.CatId = t1.CatId
)
SELECT *
FROM CTE
WHERE Seq = 1
OR Date IS NULL