-1

I don't understand how to optimize my subquery:

SELECT *
FROM rp_clientAffectationHistory as T1
WHERE rp_clientAffectationHistoryID in (SELECT MAX(rp_clientAffectationHistoryID)
        FROM rp_clientAffectationHistory as T2
GROUP BY `rp_clientID`)
AND `rp_userID` = 57

I have many duplicate entries for the same "rp_clientID"; I want only records which have the latest rp_clientAffectationHistoryID.

philipxy
  • 14,867
  • 6
  • 39
  • 83
IsraGab
  • 4,819
  • 3
  • 27
  • 46

3 Answers3

1

What you need is something like:

SELECT *
  FROM Rp_Clientaffectationhistory AS T1
left join Rp_Clientaffectationhistory as T2 on (T1.Rp_Clientid = T2.Rp_Clientid) and T1.Rp_Clientaffectationhistoryid < T2.Rp_Clientaffectationhistoryid
where T2.Rp_Clientaffectationhistoryid is null
and T1.Rp_Userid = 57

Does it help?

Matthias
  • 3,582
  • 2
  • 30
  • 41
wraith
  • 351
  • 3
  • 18
  • Also can see http://stackoverflow.com/questions/121387/fetch-the-row-which-has-the-max-value-for-a-column?rq=1 – wraith Dec 06 '13 at 09:39
0

I guess you want to get only one entry for every rp_clientID -

The one thing you missed is to check rp_clientID inside the inner query -

SELECT *
  FROM Rp_Clientaffectationhistory AS T1
 WHERE Rp_Clientaffectationhistoryid IN
       (SELECT MAX(Rp_Clientaffectationhistoryid)
          FROM Rp_Clientaffectationhistory AS T2
         WHERE T1.Rp_Clientid = T2.Rp_Clientid
         GROUP BY Rp_Clientid)
   AND Rp_Userid = 57

is it what you were looking for?

pratik garg
  • 3,282
  • 1
  • 17
  • 21
0

For Sql server, try:

SELECT * FROM(
    SELECT *, ROW_NUMBER() over (partition by rp_userID order by rp_clientAffectationHistoryID desc) Rnum 
    FROM rp_clientAffectationHistory
    WHERE rp_userID = 57
)x
WHERE Rnum=1
TechDo
  • 18,398
  • 3
  • 51
  • 64