每天选择第一个和最后一个记录

时间:2014-06-24 08:50:38

标签: sql sql-server sql-server-2008

我有一个包含一个engineerID的表,DateTimeCreated作为DateTime,JobID和AuditTypeID

我需要在查询的每一行首先显示查询(engineerID,带有AuditTypeID 1的JobID)和最后一个(engineerID,带有AuditTypeID 2的JobID)。

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

我的查询的第一部分。不幸的是,我无法看到每天选择第一条记录

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

首先获取您需要的数据,包括创建日期。然后按日期对该数据进行分组,选择每天的最小值。最后,加入两组,只选择每天的最小值 - 即每天的第一次出现。

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;

要获取每天的最后一项,只需将max添加到FirstByDay并添加到联接。如果你真的想要,可以把它分成一排。

顺便说一句,几年前我没有听到MSSQL的后续版本忽略了top (100) percent?这些天我没有用它,我的记忆是......好吧,只是......在这附近...