SQL:Inner Join根据条件返回一行

时间:2014-12-31 20:30:27

标签: sql sql-server linq select inner-join

这可能很简单,但我正在寻找原始SQL来执行INNER JOIN,但只根据条件返回第二个表中的一个匹配项。

给出两个表:

**TableOne**   
 ID  Name  
 1   abc  
 2   def

**TableTwo**  
 ID    Date     
 1     12/1/2014
 1     12/2/2014
 2     12/3/2014
 2     12/4/2014
 2     12/5/2014

我想加入,但只返回第二张表中的最新日期:

Expected Result:
1   abc   12/2/2014
2   def   12/5/2014

我可以在LINQ中轻松完成此操作:

TableOne.Select(x=> new { x.ID, x.Name, Date = x.TableTwo.Max(y=>y.Date) });

换句话说,上面的LINQ语句在原始SQL中转化为什么?

4 个答案:

答案 0 :(得分:5)

有两种方法可以做到这一点:

  1. 使用GROUP BYMAX()

    SELECT one.ID,
           one.Name,
           MAX(two.Date)
        FROM TableOne one
            INNER JOIN TableTwo two on one.ID = two.ID
        GROUP BY one.ID, one.Name
    
  2. ROW_NUMBER()与CTE一起使用:

    ; WITH cte AS (
        SELECT one.ID,
           one.Name,
           two.Date,
           ROW_NUMBER() OVER (PARTITION BY one.ID ORDER BY two.Date DESC) as rn
        FROM TableOne one
           INNER JOIN TableTwo two ON one.ID = two.ID
    )
        SELECT ID, Name, Date FROM cte WHERE rn = 1
    

答案 1 :(得分:3)

您可以使用聚合查询加入第一个表:

SELECT t1.id, d
FROM   TableOne t1
JOIN   (SELECT   id, MAX[date] AS d
        FROM     TableTwo
        GROUP BY id) t2 ON t1.id = t2.id

答案 2 :(得分:1)

类似的东西:

SELECT TableOne.id, TableOne.name, MAX(TableTwo.Date)
FROM TableOne
LEFT JOIN TableTwo ON TableOne.id = TableTwo.id
GROUP BY TableOne.id, TableOne.name;

连接将生成一个包含TableTwo的行数的表,但group by将根据TableOne的行将其过滤为一行。

答案 3 :(得分:1)

由于没有其他人已经覆盖了将执行您想要的任务的公用表表达式(CTE),我将把它扔到这里:

with maxDates as (
    select Id, max(Date)
    from Table2
    group by Id
)
select x.Id, x.Name, y.Date
from TableOne x
inner join maxDates y
on x.Id = y.id