-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,416
  • 5
  • 32
  • 77
IsraGab
  • 4,293
  • 3
  • 23
  • 40

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,536
  • 2
  • 30
  • 39
wraith
  • 341
  • 3
  • 16
  • 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,212
  • 1
  • 16
  • 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
  • 17,954
  • 3
  • 48
  • 63