views:

119

answers:

2

I got a join select statement and i only need the last modified field in the second table. here's the select statement that i have now:

SELECT  NOM,PRENOM,OEDP.NUM_EMP,N_A_S,SIT_STATUT,PERMIS,DATE_EMBAUCHE,ADRESSE1,VILLE1,PROVINCE1,CODE_POSTAL1,TEL_RESIDENCE
FROM    ODS_EMPLOYE_DOSSIER_PERSONNEL AS OEDP
JOIN    ODS_SITUATION_POSTE AS OSP
ON      OEDP.NUM_EMP = OSP.NUM_EMP
WHERE   SIT_DATE_CHG = MAX(SIT_DATE_CHG)
ORDER BY
        OEDP.NUM_EMP

i got the folowing erreur msg :

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

+2  A: 
SELECT  NOM,PRENOM,OEDP.NUM_EMP,N_A_S,SIT_STATUT,PERMIS,DATE_EMBAUCHE,ADRESSE1,VILLE1,PROVINCE1,CODE_POSTAL1,TEL_RESIDENCE
FROM    ODS_EMPLOYE_DOSSIER_PERSONNEL AS OEDP
CROSS APPLY 
        (
        SELECT  TOP 1 *
        FROM    ODS_SITUATION_POSTE AS OSP
        WHERE   OEDP.NUM_EMP = OSP.NUM_EMP
        ORDER BY
                SIT_DATE_CHG DESC
        ) OSP
ORDER BY
        OEDP.NUM_EMP

Actually, there are several methods to do this, and their efficiency depends on how the data are distributed across the tables.

See this article in my blog for comparison of these methods:

Quassnoi
CROSS APPLY?????
Hogan
`@Hogan`: `CROSS APPLY`!!!!!
Quassnoi
@Quassnoi: Isn't the 2nd example I gave better? (I guess it won't work for pre 2005)
Hogan
`@Hogan`: your solution will return ties in case of duplicates on the date field.
Quassnoi
@Q : You said mine will return ties too... but this won't?? -- Anyway, this one is is O(N1*N2) and mine is O(N1+N2) that does not seem good.
Hogan
`@Hogan`: no, this won't. You better read the article and see the actual execution plans. `SQL Server` is much smarter than `O(N1*N2)`
Quassnoi
@Q: Nice article -- I'm still trying to absorb it.
Hogan
A: 
SELECT TOP 1  NOM,PRENOM,OEDP.NUM_EMP,N_A_S,SIT_STATUT,PERMIS,DATE_EMBAUCHE,ADRESSE1,VILLE1,PROVINCE1,CODE_POSTAL1,TEL_RESIDENCE
FROM    ODS_EMPLOYE_DOSSIER_PERSONNEL AS OEDP
JOIN    ODS_SITUATION_POSTE AS OSP ON OEDP.NUM_EMP = OSP.NUM_EMP
ORDER BY SIT_DATE_CHG DESC

With 2005 for all employees would be something like this:

WITH LastUserInfo AS
(
  SELECT NUM_EMP, MAX(SIT_DATE_CHG) AS SIT_DATE_CHG
  FROM    ODS_EMPLOYE_DOSSIER_PERSONNEL AS OEDP
  JOIN    ODS_SITUATION_POSTE AS OSP
  ON      OEDP.NUM_EMP = OSP.NUM_EMP
  GROUP BY NUM_EMP
)
SELECT  NOM,PRENOM,OEDP.NUM_EMP,N_A_S,SIT_STATUT,PERMIS,DATE_EMBAUCHE,ADRESSE1,VILLE1,PROVINCE1,CODE_POSTAL1,TEL_RESIDENCE
FROM    ODS_EMPLOYE_DOSSIER_PERSONNEL AS OEDP
JOIN    ODS_SITUATION_POSTE AS OSP
ON      OEDP.NUM_EMP = OSP.NUM_EMP
INNER JOIN LastUserInfo L ON NUM_EMP = L.NUM_EMP AND SIT_DATE_CHG = L.SIT_DATE_CHG
ORDER BY
        OEDP.NUM_EMP
Hogan
This will return all ties in case of duplicates on `SIT_DATE_CHG`.
Quassnoi