2008-10-31 7 views
2

J'ai deux tables:Aide sql rejoindre

Tableau 1: ID, PersonCode, Nom,

Tableau 2: ID, Table1ID, Emplacement, ServiceDate

J'ai un requête joignant la table 1 à la table 2 sur table1.ID = table2.Table1ID où PersonCode = 'XYZ'

Ce que je veux faire est de retourner Table1.PersonCode, Table1.Name, Table2.Location, Table2.ServiceDate, I don Je ne veux pas toutes les lignes, Dans le tableau 2, je ne suis intéressé que par Il rang avec le ServiceDate le plus récent pour chaque emplacement. Comment ferais-je cela?

Répondre

3

Quelque chose comme ceci:

SELECT 
    Table1.PersonCode, Table1.Name, Table2.Location, MAX(Table2.ServiceDate) 
FROM 
    Table1 
    INNER JOIN Table2 on Table1.ID = Table2.Table1ID 
WHERE 
    TABLE1.PersonCode = 'XYZ' 
GROUP BY 
    Table1.PersonCode,Table1.Name, Table2.Location 
+0

Pourquoi LEFT JOIN? Je pensais que INNER JOIN est suffisant? Je voudrais modifier votre requête - S'il vous plaît voir ma réponse ci-dessous –

+0

Désolé, je travaillais sur une autre question avec jointures à gauche - édité –

0

Utilisez MAX (ServiceDate)

0

Essayez:

select Table1.PersonCode,Table1.Name, Table2.Location, Table2.ServiceDate 
from Table1 
join Table2 on table1.ID = table2.Table1ID 
where table1.PersonCode = 'XYZ' 
and table2.ServiceDate = (select max(t2.ServiceDate) 
          from table2 t2 
          where t2.table1ID = table2.table1ID 
          and t2.location = table2.location 
         ); 
0

J'utiliser un INNER JOIN et sélectionnez le premier enregistrement, après avoir ordonné aux dossiers en marche arrière ordre chronologique basé sur Table2.ServiceDate.

SELECT TOP 1 
    Table1.PersonCode, Table1.Name, Table2.Location, Table2.ServiceDate 
FROM 
    Table1 
    INNER JOIN Table2 on Table1.ID = Table2.Table1ID 
WHERE 
    TABLE1.PersonCode = 'XYZ' 
ORDER BY Table2.ServiceDate DESC 
GROUP BY 
    Table1.PersonCode,Table1.Name, Table2.Location