2012-01-17 118 views
4
的最後一個記錄

可能重複:
Retrieving the last record in each groupMySQL來得到重複的條目

大家好我有如下

ID FedTaxID RegularPay Payperiodnumber 

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

我想我的表數據得到我的數據如下

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

我嘗試了一些東西一樣如下,但我沒有得到需要的結果

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

任何一個可以幫助我

+3

http://stackoverflow.com/questions/1313120/ – newtover 2012-01-17 12:33:16

+0

'newtover'完美的感謝:-) – Dotnet 2012-01-17 12:38:05

回答

6

這應該給你想要的結果:

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'; 

我對新發布的鏈接感興趣;但在這種情況下,您需要每個payperiod編號的最大編號,因此您必須更多地適應這一點。它看起來像這樣:

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' 

這是更簡單的閱讀。非常感謝@BillKarwin提供的一整套基於解決方案。感謝您有機會學習一種新的(並且更好地給出鏈接發佈)的方式。

+0

這一個也有效,但更簡單的是[檢查](http://stackoverflow.com/questions/1313120/retrieving - 最後一個記錄在每個組) – Dotnet 2012-01-17 12:40:36

+0

標記爲答案,因爲它解決了 – Dotnet 2012-01-17 12:41:56