2015-06-17 67 views
0

我根據利用我需要在我的節目中所有信息的幾個連接表中的SQL Server 2008 R2中的SQL語句:SQL - 如何僅基於ID顯示具有最大日期值的行?

SELECT 
    Laptops.Laptop_ID, 
    Laptops.Model_Name, 
    ... 
    Users.Firstname + Users.Lastname AS Name, 
    Loans.Date_Loaned 
FROM Users 
    INNER JOIN Loans ON Users.User_ID = Loans.User_ID 
    RIGHT OUTER JOIN Laptops ON Loans.Laptop_ID = Laptops.Laptop_ID 

這帶來了類似的一個表:

ID Model_Name ... Name Date_Loaned 
1 ...  ... Kris 18-08-11 
2 ...  ... Jo  20-08-11 
2 ...  ... Bert 18-08-11 
4 ...  ... Sam 19-08-11 

我正在試圖做的是那裏將重複ID,我想只顯示最高日行,像這樣:

ID Model_Name ... Name Date_Loaned 
1 ...  ... Kris 18-08-11 
2 ...  ... Jo  20-08-11 
4 ...  ... Sam 19-08-11 

我有PROBL ems搞清楚如何用我已經擁有的SQL語句來做到這一點。幫幫我!

+0

三這裏的答案可能是最好的技術爲您提供:http://stackoverflow.com/a/24863984/84206 – AaronLS

回答

1

使用Windows功能:

SELECT * FROM(
       SELECT Laptops.Laptop_ID, 
        Laptops.Model_Name, 
        ... 
        Users.Firstname + Users.Lastname AS Name, 
        Loans.Date_Loaned, 
        row_number() 
         over(partition by Laptops.Laptop_ID 
          order by Loans.Date_Loaned desc) rn 
       FROM Users 
       INNER JOIN Loans ON Users.User_ID = Loans.User_ID 
       RIGHT OUTER JOIN Laptops ON Loans.Laptop_ID = Laptops.Laptop_ID) t 
WHERE rn = 1 
+0

看起來像那樣做!非常感謝! –

0

試試這個

SELECT Laptops.Laptop_ID, 
Laptops.Model_Name, 
... 
Users.Firstname + Users.Lastname AS Name, 
MAX(Loans.Date_Loaned) AS date 
FROM Users 
INNER JOIN Loans ON Users.User_ID = Loans.User_ID 
RIGHT OUTER JOIN Laptops ON Loans.Laptop_ID = Laptops.Laptop_ID 
GROUP BY Laptops.Laptop_ID, 
Laptops.Model_Name, 
... 
Users.Firstname + Users.Lastname AS Name 
+0

我已經嘗試過,我改變了我的問題稍微來解決這個問題。當我這樣做時,它將只有具有相同名稱(用戶)的行的最大日期。我只需要它通過Laptop_ID分組,但它不會像那樣工作 –

0

很高興你有你的答案,只是想提一提,你可能會得到更好的性能選擇從LaptopsLEFT OUTER JOIN用戶/貸款子查詢。由於RIGHT OUT JOIN不經常使用,因此下一個人可能會更容易解密。使用別名還有助於消除某些鍵入。

SELECT 
    l.Laptop_ID, 
    l.Model_Name, 
    ul.Name, 
    ul.Date_Loaned 
FROM 
    Laptops l 
    LEFT JOIN (
      SELECT l.Laptop_ID, 
        u.Firstname + u.Lastname AS Name, 
        l.Date_Loaned, 
        ROW_NUMBER() OVER(PARTITION BY l.Laptop_ID ORDER BY l.Date_Loaned desc) Rn 
      FROM Loans l 
        JOIN Users u ON l.User_ID = u.User_ID 
    ) ul ON l.Laptop_ID = ul.Laptop_ID 
      AND ul.Rn = 1