帮助处理不同的行和数据排序

时间:2008-11-19 21:21:28

标签: sql sql-server

如果我有记录:

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

我需要获取行(datelocatinidaccount),其中行包含每个不同locationid的最新日期:

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

尝试类似:

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

答案 2 :(得分: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 

答案 3 :(得分: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只返回一行,即使有多行具有相同的最大日期。