2016-11-19 55 views
1

行不同:SQL Where子句變量需要按所給的以下數據

ID, Name, Location, Date 
1, Tom, Boston, 8/12/2015 
1, Tom, Lowell, 7/12/2015 
1, Tom, Wakefield, 6/12/2015 
2, Jake, Salem, 12/15/2018 
2, Jack, Worcester, 5/12/2015 

如何將一個寫一個SQL查詢,該查詢將返回僅含有最大日的行的表,例如:

ID, Name, Location, Date 
1, Tom, Boston, 8/12/2015 
2, Jake, Salem, 12/15/2018 

假設IDName是固定密鑰。但是,location可能是可變的,應該返回的location將與最大的date關聯。

我最近的嘗試目前僅返回所有日期的MAX,而不是最大日期爲ID/Name對的記錄。例如:

SELECT ID, NAME, Location, Data 
FROM Table A 
WHERE Date = (SELECT MAX(Date) FROM Table B WHERE A.ID = B.ID and A.Name = B.Name) 

僅產生:

2, Jake, Salem, 12/15/2018 

回答

2

方法1:

SELECT A.* FROM [Table] A 
JOIN (
    SELECT ID, Name, MAX([Date]) MaxDate 
    FROM [Table] 
    GROUP BY ID, Name 
) B ON B.ID = A.ID AND B.Name = A.Name AND B.MaxDate = A.[Date] 

方法2:

SELECT ID, Name, [Location], [Date] FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ID, Name ORDER BY [Date] DESC) R 
    FROM [Table] 
) T 
WHERE R = 1 

例子:

DECLARE @T TABLE (
    ID INT, 
    Name VARCHAR(16), 
    [Location] VARCHAR(16), 
    [Date] DATE 
) 

INSERT @T VALUES 
(1, 'Tom', 'Boston', '8/12/2015'), 
(1, 'Tom', 'Lowell', '7/12/2015'), 
(1, 'Tom', 'Wakefield', '6/12/2015'), 
(2, 'Jake', 'Salem', '12/15/2018'), 
(2, 'Jack', 'Worcester', '5/12/2015') 

SELECT A.* FROM @T A 
JOIN (
    SELECT ID, Name, MAX([Date]) MaxDate 
    FROM @T 
    GROUP BY ID, Name 
) B ON B.ID = A.ID AND B.Name = A.Name AND B.MaxDate = A.[Date] 

SELECT ID, Name, [Location], [Date] FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ID, Name ORDER BY [Date] DESC) R 
    FROM @T 
) T 
WHERE R = 1 
+0

謝謝!很好的例子。 – thaynes

2

事情是這樣工作的:

select ID, Name, Location, Date 
from (
    select *, row_number() over (partition by ID order by Date desc) as RN 
    from yourtable 
) X 
where RN = 1 

行數量將增加一個序列號的行,按日期遞減,並且分區通過它每次ID改變時它將重新開始編號。

如果您需要獲取多行的情況下,有一個與在同一天幾行,然後使用秩(),而不是ROW_NUMBER()

1

您可以通過Id場分組查找最大日期。然後用主表join找到最終結果。

SELECT X.* 
FROM @T X INNER JOIN 
        (
         SELECT A.ID,MAX(A.Date) MaxDate 
         FROM @T A 
         GROUP BY A.ID 
             ) Y 
ON X.ID = Y.Id AND x.Date = Y.MaxDate 
ORDER BY Y.ID 
0

你也可以這樣試試:

SELECT a.ID, a.NAME, a.Location, a.Date 
FROM Table a 
LEFT JOIN Table as b 
ON b.ID = a.ID AND b.Date > a.Date 
WHERE b.ID is NULL 
0

試試這個

Select ID,Name,Location,max(Date) as Date 
FROM table_name 
group by ID 

希望這個作品。

+0

最簡單的以下所有答案。 –

+0

我早些時候嘗試過,但它最終抱怨我需要將名稱和位置添加到Group by子句。 – thaynes

+1

該聲明格式錯誤,因爲'Name'和'Location'不在GROUP BY子句中。 –

0

你靠近。嘗試將GROUP BY添加到子查詢中,並將=更改爲IN

SELECT ID, NAME, Location, [Date] 
FROM Table A 
WHERE Date in ( 
       SELECT MAX(Date) 
       FROM Table B 
       WHERE A.ID = B.ID and A.Name = B.Name 
       GROUP BY ID, Name ) 

另一種更好的方法是創建你的子查詢view和視圖join表。