2008-11-19 7 views
0

Si je disques:aide avec des lignes distinctes et les données de commande

 
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 

Je dois obtenir la ligne (date, locatinid, account) où la ligne a pour chaque locationid distincte la date la plus récente:

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

Répondre

2

Je pense que cela fonctionnerait:

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

Merci, a travaillé comme un charme. J'ai en fait ajouté une expression de table commune pour table car la clause where était assez impliquée dans mon scénario, et je voulais éviter de l'écrire deux fois dans le select externe et le select interne. – Jeremy

0

Essayez quelque chose comme:

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

Il a le petit problème que si vous avez deux entrées à la même date exacte, vous pourriez obtenir deux résultats. –

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

J'ai eu la même solution, je viens d'utiliser une syntaxe différente pour effectuer la jointure. – Jim

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; 

Cette solution renvoie une seule ligne par emplacementid, même s'il existe plusieurs lignes avec la même date max.

Questions connexes