简体   繁体   中英

Select first and last record each day

I have a table with an engineerID, DateTimeCreated as DateTime, JobID and AuditTypeID

I need a query shows first (engineerID, JobID with AuditTypeID 1) and last (engineerID, JobID with AuditTypeID 2) on each row of the query.

SELECT TOP (100) PERCENT 
    dbo.AuditTrail.EngineerId, 
    dbo.AuditTrail.AuditTypeId, 
    dbo.Engineers.Name, 
    dbo.Engineers.EngineerTypeCode, 
    dbo.AuditTrail.JobId, 
    CAST(dbo.AuditTrail.DateTimeCreated AS Date) AS _Date
FROM
    dbo.AuditTrail 
INNER JOIN
    dbo.Engineers 
    ON dbo.AuditTrail.EngineerId = dbo.Engineers.EngineerId
WHERE        
    (dbo.AuditTrail.AuditTypeId = 1) AND 
    (dbo.Engineers.EngineerTypeCode = 'p') AND 
    (dbo.Engineers.EngineerTypeCode = 'p') AND 
    (DATEPART(mm, dbo.AuditTrail.DateTimeCreated) = 6) AND 
    (DATEPART(YYYY, dbo.AuditTrail.DateTimeCreated) = 2014)    
group by 
    AuditTrail.engineerID, 
    JobID, 
    AuditTypeId, 
    Engineers.name, 
    Engineers.EngineerTypeCode, 
    CAST(dbo.AuditTrail.DateTimeCreated AS Date)
ORDER BY 
    dbo.AuditTrail.EngineerID DESC

for the first part of my query. Unfortunatly I cannot see to select the first record for each day

Any help will be greatly appreciated

First just get the data you need, including the create date. Then grouping that data by date, select the min of each day. Finally, join the two sets, selecting only the minimum of each day -- that is, the first occurrence of each day.

with
AllMonth( EngineerId, AuditTypeId, Name, EngineerTypeCode, JobId, DateTimeCreated )as(
  SELECT TOP (100) PERCENT 
      a.EngineerId, 
      a.AuditTypeId, 
      e.Name, 
      e.EngineerTypeCode, 
      a.JobId, 
      a.DateTimeCreated
  FROM  dbo.AuditTrail a
  JOIN  dbo.Engineers  e
    ON  e.EngineerId = a.EngineerId
   AND  e.EngineerTypeCode = a.EngineerTypeCode
  WHERE        
        a.AuditTypeId = 1
    AND a.EngineerTypeCode = 'p'
    AND a.DateTimeCreated >= DateAdd( mm, DateDiff( mm, 0, GetDate()), 0)
    AND a.DateTimeCreated < DateAdd( mm, DateDiff( mm, 0, GetDate()) + 1, 0)
),
FirstByDay( MinDate )as(
  select  Min( DateTimeCreated )
  from    AllMonth
  group by cast( DateTimeCreated AS Date )
)
select  *
from    AllMonth a
join    FirstByDay f
  on    f.MinDate = a.DateTimeCreated
ORDER BY a.EngineerID DESC;

To get the last item of each day, just add a max to FirstByDay and add to the join. Work it into one long row if you really want to.

Btw, didn't I hear a few years back that the later versions of MSSQL ignored top (100) percent ? I don't work with it much these days, and my memory is...well, just...somewhere around here...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM