2017-07-31 55 views
1

無法在此上看到樹木,我相信它很簡單。 我試圖返回最大ID的相關記錄在連接表帶有內部連接的MS-SQL最大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 

回答

0

這是我怎麼會做了,我想IDValueNULL當表2沒有對錶1的記錄對應的條目:

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 
+0

感謝更換't2',該工作一個魅力,稍微mod'd使用內部連接,因爲其他表是依賴。 – BigIWT

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。

+0

如果您需要的名稱,修改戈登的SQL與'T2 INNER JOIN表1 ON t2.nid = table1.nid'和更新選擇列表,以反映你想要什麼 –

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 
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