我有下表:
| ID | ExecOrd | date |
| 1 | 1.0 | 3/4/2014|
| 1 | 2.0 | 7/7/2014|
| 1 | 3.0 | 8/8/2014|
| 2 | 1.0 | 8/4/2013|
| 2 | 2.0 |12/2/2013|
| 2 | 3.0 | 1/3/2014|
| 2 | 4.0 | |
我需要获得大约8000条记录的每date
个ExecOrd
ID
,到目前为止,我只能为ID
个SELECT TOP 1 date
FROM TABLE
WHERE DATE IS NOT NULL and ID = '1'
ORDER BY ExecOrd DESC
执行此操作:
{{1}}
一点帮助将不胜感激。我一直试图找到类似的问题而没有成功。
答案 0 :(得分:1)
有几种方法可以做到这一点。通用方法是使用max()
:
select t.date
from yourtable t
join (select max(execord) execord, id
from yourtable
group by id
) t2 on t.id = t2.id and t.execord = t2.execord
如果你正在使用2005年以上,我更喜欢使用row_number()
:
select date
from (
select row_number() over (partition by id order by execord desc) rn, date
from yourtable
) t
where rn = 1;
注意:如果存在关系,它们将给出不同的结果。
答案 1 :(得分:0)
;with cte as (
SELECT id,row_number() over(partition by ID order byExecOrd DESC) r
FROM TABLE WHERE DATE IS NOT NULL )
select id from
cte where r=1