1

I need distinct Jobid with recent status

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

I need result like this

---------------
JobId  Status
---------------
1       Sent
2       Sent 

I tried this but giving duplicate jobids with different statuses records

select distinct JobId, Status, CreatedDate from Jobs order by CreatedDate desc
Diya
  • 31
  • 4

3 Answers3

0

I would suggest:

select j.*
from jobs j
where j.CreatedDate = (select max(j2.CreatedDate) from jobs j2 where j2.jobid = j.jobid);

If you have an index on jobs(jobid, CreatedDate), then this is probably the fastest option.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Try This:

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
Rahul Jain
  • 1,319
  • 7
  • 16
0

Considering you are using SQL Server version that supports Common-Table-Expressions, I would use following query:

;with cte as (
    select 
        *, 
        ROW_NUMBER() over (PARTITION BY JobId ORDER BY CreatedDate desc) AS RN 
    from jobs)

select * from cte where RN = 1
GSazheniuk
  • 1,340
  • 10
  • 16