有限的T-SQL加入

时间:2009-06-22 14:02:52

标签: sql-server tsql join limit

这应该很简单,但不知怎的,我的大脑停止了工作。

我有两个相关的表格:

表1:

ID (PK), Value1

表2:

BatchID, Table1ID (FK to Table 1 ID), Value2

示例数据:

表1:

ID  Value1
1   A
2   B

表2:

BatchID  Table1ID  Value2
1        1         100
2        1         101
3        1         102
1        2         200
2        2         201

现在,对于表1中的每条记录,我想在表2中进行匹配记录,但只有最新的记录(批次ID是顺序的)。以上示例的结果将是:

Table1.ID  Table1.Value1  Table2.Value2
1          A              102
2          B              201

问题很简单,如何用Table2限制连接结果。 SO上有类似的问题,但找不到像我这样的东西。这是一个看起来类似的MySQL: LIMITing an SQL JOIN

我对任何方法持开放态度,尽管速度仍然是主要优先事项,因为它将成为一个大数据集。

4 个答案:

答案 0 :(得分:10)

WITH Latest AS (
    SELECT Table1ID
        ,MAX(BatchID) AS BatchID
    FROM Table2
    GROUP BY Table1ID
)
SELECT *
FROM Table1
INNER JOIN Latest
    ON Latest.Table1ID = Table1.ID
INNER JOIN Table2
    ON Table2.BatchID = Latest.BatchID

答案 1 :(得分:3)

SELECT  id, value1, value2
FROM    (
        SELECT  t1.id, t2.value1, t2.value2, ROW_NUMBER() OVER (PARTITION BY t1.id ORDER BY t2.BatchID DESC) AS rn
        FROM    table1 t1
        JOIN    table2 t2
        ON      t2.table1id = t1.id
        ) q
WHERE   rn = 1

答案 2 :(得分:0)

尝试

select t1.*,t2.Value2
from(
select Table1ID,max(Value2) as Value2
from [Table 2]
group by Table1ID) t2
join [Table 1] t1 on t2.Table1ID = t1.id

答案 3 :(得分:-1)

过滤最近的GROUP BY或WHERE子句:

SELECT * FROM Table1 a
INNER JOIN Table2 b ON (a.id = b.Table1ID)
WHERE NOT EXISTS(
      SELECT 1 FROM Table2 c WHERE c.Table1ID = a.id AND c.BatchID > b. BatchID
)