具有内部联接的MS-SQL最大ID

时间:2017-07-31 14:00:24

标签: sql sql-server

在这上面看不到树木的木材,我确信它很简单。 我试图在连接表中返回相关记录的最大ID

表1

NiD     Name    
1       Peter
2       John
3       Arthur

表2

ID   NiD     Value     
1    1       5         
2    2       10
3    3       10
4    1       20
5    2       15

最大结果

NiD   ID    Value
1     4     20
2     5     15
3     3     10

4 个答案:

答案 0 :(得分:0)

您可以使用row_number()

select NiD, ID, Value
from (select t2.*,
             row_number() over (partition by NiD order by ID desc) as seqnum
      from table2 t2
     ) t2
where seqnum = 1;

如上所述,您不需要table1,因为table2包含所有ID。

答案 1 :(得分:0)

CREATE TABLE Names
(
    NID INT,
    [Name] VARCHAR(MAX)
)

CREATE TABLE Results
(
    ID INT,
    NID INT,
    VALUE INT
)

INSERT INTO Names VALUES (1,'Peter'),(2,'John'),(3,'Arthur')
INSERT INTO Results VALUES (1,1,5),(2,2,10),(3,3,10),(4,1,20),(5,2,15)

SELECT  a.NID,
        r.ID,
        a.MaxVal
FROM    (
            SELECT  NID,
                    MAX(VALUE) as MaxVal
            FROM    Results r
            GROUP BY NID
        ) a
        JOIN Results r
            ON a.NID = r.NID AND a.MaxVal = r.VALUE
ORDER BY NID

答案 2 :(得分:0)

我就是这样做的,当Table2没有Table1记录的相应条目时,我认为IDValue将是NULL

SELECT NiD, ID, [Value]
FROM Table1
OUTER APPLY (
    SELECT TOP 1 ID, [Value]
    FROM Table2
    WHERE Table1.NiD = Table2.NiD
    ORDER BY [Value] DESC
) AS Top_Table2

答案 3 :(得分:0)

这是我在类似情况下使用的,性能很好,前提是数据集不是太大(在1M行以下)。

SELECT 
    table1.nid
    ,table2.id
    ,table2.value
FROM table1
INNER JOIN table2 ON table1.nid = table2.nid
WHERE table2.value = (
    SELECT MAX(value)
    FROM table2
    WHERE nid = table1.nid)
ORDER BY 1