Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mySql to get last records of duplicate entries [duplicate]

Tags:

mysql

Possible Duplicate:
Retrieving the last record in each group

Hi all i am having my table data as follows

ID   FedTaxID  RegularPay  Payperiodnumber

1    562545366   500            1
2    562545366   501            1
3    562545366   5000           2

I would like to get my data as follows

 ID    FedTaxID    RegularPay   Payperiodnumber
 2     562545366     501            1
 3     562545366     5000           2

I tried some thing like as follow but i am not getting the required result

select max(id) ID,regularpay,fedtaxid,payperiodnumber
from tblemployeegrosswagesn1 where fedtaxid="562545366"
group by payperiodnumber
having count(*) >= 1;

Can any one help me

like image 811
Developer Avatar asked Jan 17 '12 12:01

Developer


1 Answers

This should give you the desired result:

SELECT      t.ID, 
            t.FedTaxID, 
            t.RegularPay, 
            t.Payperiodnumber

FROM        tblemployeegrosswagesn1 t
INNER JOIN  (SELECT MAX(ID) AS MaxId, 
                    FedTaxID, 
                    Payperiodnumber 
             FROM  tblemployeegrosswagesn1  
             GROUP BY FedTaxID, Payperiodnumber) AS InnerQuery ON t.ID = InnerQuery.MaxId AND t.Payperiodnumber = InnerQuery.Payperiodnumber AND t.FedTaxID = InnerQuery.FedTaxID

WHERE        t.FedTaxID = '562545366';

I am intrigued by the link newtover posted; In this instance, though, you want the max id per payperiodnumber so you'll have to adapt that a bit more. It will look something like:

SELECT              t.Id,
                    t.FedTaxId,
                    t.RegularPay,
                    t.Payperiodnumber

FROM                tblemployeegrosswagesn1 t

LEFT JOIN           tblemployeegrosswagesn1 t1  ON (t.FedTaxId = t1.FedTaxId AND t.Payperiodnumber = t1.PayperiodNumber AND t.id < t1.id)   

WHERE               t1.ID IS NULL   
AND                 t.FedTaxId = '562545366'

Which is much simpler to read. Many thanks to @BillKarwin for a neat set based solution. Thanks for the chance to learn a new (and better given the link posted) way of doing something.

like image 93
dash Avatar answered Oct 07 '22 09:10

dash