我需要具有近期状态的独特Jobid
jobs table
------------------
JobId Status CreatedDate
------------------
1 sent 4/24/2018
1 draft 4/23/2018
2 sent 4/22/2018
2 draft 4/21/2018
1 req 4/20/2018
我需要这样的结果
---------------
JobId Status
---------------
1 Sent
2 Sent
我尝试了这个但是给出了具有不同状态记录的重复jobid
select distinct JobId, Status, CreatedDate from Jobs order by CreatedDate desc
答案 0 :(得分:0)
我建议:
select j.*
from jobs j
where j.CreatedDate = (select max(j2.CreatedDate) from jobs j2 where j2.jobid = j.jobid);
如果你有jobs(jobid, CreatedDate)
的索引,那么这可能是最快的选择。
答案 1 :(得分:0)
试试这个:
SELECT
JobId,
Status
FROM
jobs j,
(
SELECT JobId, max(CreatedDate) cd
FROM jobs
GROUP BY JobId
) as t
where j.jobid = t.jobid
and cd = j.CreatedDate
答案 2 :(得分:0)
考虑到您使用的是支持Common-Table-Expressions的SQL Server版本,我将使用以下查询:
;with cte as (
select
*,
ROW_NUMBER() over (PARTITION BY JobId ORDER BY CreatedDate desc) AS RN
from jobs)
select * from cte where RN = 1