2008-11-19 41 views
0

如果我有記錄:幫助具有鮮明行和數據排序

 
Row Date,  LocationID, Account 
1 Jan 1, 2008 1   1000 
2 Jan 2, 2008 1   1000 
3 Jan 3, 2008 2   1001 
4 Jan 3, 2008 1   1001 
5 Jan 3, 2008 3   1001 
6 Jan 4, 2008 3   1002 

我需要得到其中行具有最新的每個不同的locationid日期行(datelocatinidaccount):

 
4 Jan 3, 2008 1   1001 
3 Jan 3, 2008 2   1001 
6 Jan 4, 2008 3   1002 

回答

2

,我認爲這會工作:

SELECT t1.* 
FROM table t1 
    JOIN (SELECT MAX(Date), LocationID 
     FROM table 
     GROUP BY Date, LocationID) t2 on t1.Date = t2.Date and t1.LocationID = t2.LocationID 
+0

謝謝,像一個魅力工作。我實際上爲表添加了一個公用表表達式,因爲where子句與我的場景非常相關,我想避免在外部select和內部select中寫出兩次。 – Jeremy 2008-11-20 00:27:08

0

嘗試類似:

select * 
from mytable t1 
where date = (select max(date) from mytable t2 
       where t2.location = t1.location); 
+0

它有小問題,如果你有兩個條目具有完全相同的日期,你可能會得到兩個結果。 – 2008-11-19 21:28:31

0
select t.* from mytable t, 
(select max(Date) as Date,LocationID from mytable group by LocationID) t1 
where t.Date = t1.Date and t.LocationID = t1.LocationID 
order by t1.LocationID 
+0

我有相同的解決方案,我只是使用不同的語法來執行連接。 – Jim 2008-11-19 22:01:21

0
SELECT t1.* 
FROM mytable t1 
    LEFT OUTER JOIN mytable t2 
    ON (t1.locationid = t2.locationid 
    AND (t1.date < t2.date OR t1.date = t2.date AND t1.row < t2.row)) 
WHERE t2.row IS NULL; 

即使存在多個具有相同最大日期的行,此解決方案每個locationid只返回一行。