开发者

sql query - join that return only last row

开发者 https://www.devze.com 2022-12-16 14:50 出处:网络
I got a join select statement and i only need the last modified field in the second table. here\'s the s开发者_运维技巧elect statement that i have now:

I got a join select statement and i only need the last modified field in the second table. here's the s开发者_运维技巧elect 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.


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:

  • SQL Server: Selecting records holding group-wise maximum


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
0

精彩评论

暂无评论...
验证码 换一张
取 消