如何为每个DetailId选择具有更大CreateDate的FlowId

时间:2013-09-28 10:22:54

标签: sql-server

如何为每个[DetailId]选择[FlowDd]更大的[CreateDate] 例如细节数据 enter image description here

3 个答案:

答案 0 :(得分:1)

试试这个

select * from t a
where dt = (select max(dt)
            from T b where a.detailid = b.detailid)
order by 1

SQL DEMO

答案 1 :(得分:0)

假设SQL Server 2005及更高版本,请使用类似ROW_NUMBER的排名函数:

with TopFlow as
(
  select *
    , FlowRank = row_number() over (partition by DetailID
                                   order by [Date] desc, FlowID desc)
  from MyTable
)
select DetailID
  , FlowID
  , [Date]
from TopFlow
where FlowRank = 1

SQL Fiddle with demo

答案 2 :(得分:0)

select M.*
from MyTable M
inner join 
(
select DetailID,max(Date) Date
from MyTable
Group by DetailID
)T
on M.DetailID=T.DetailID
and M.Date=T.Date
order by M.DetailID

<强> SQL Fiddle