1

我得到了下表:

Sampletable
{
 ID int, 
 PartnerID int, 
 ChangeDate datetime
}

我希望所有人都IDsPartnerID最高分组Changedate

有没有一种高效的方法,或者你会推荐其他方法来获得类似的结构?

PS:我使用的是 microsoft sql server 2012

编辑:我已经有了一种可行的方法,但我认为可能有更高效的解决方案:

Select pas.Id, pas1.ChangeDate
from Sampletable pas
inner join (SELECT PartnerID, Max(ChangeDate) as ChangeDate FRom Sampletable Group by PartnerID) pas1 on pas1.PartnerID = pas.PartnerId AND pas1.ChangeDate = pas.ChangeDate
4

2 回答 2

1

你可以试试这样...

Select ID , 
PartnerID , 
ChangeDate 
from 
( Select  Row_Number() Over (Partition by PartnerID  order by ChangeDate  Desc) as Row, Id
  PartnerID , 
  ChangeDate 
  from SampleTable
) t where row=1
于 2013-07-04T08:52:45.750 回答
0

你可以这样做:

SELECT pas.Id,
       pas.ChangeDate
FROM Sampletable pas
WHERE pas.ChangeDate = (SELECT Max(pas1.ChangeDate) 
                        FROM Sampletable pas1 
                        WHERE pas1.PartnerID = pas.PartnerId)
于 2013-07-04T09:23:05.750 回答