多个内部联接中的倒数第二个最近日期

时间:2019-05-23 15:39:53

标签: sql date group-by nested

我已根据此处找到的其他问题尝试了所有解决方案。但是我试图在查询中找到最新的PlannedEndTime。但是我很难从必须包含在这里的所有内部联接中使用语法。

我正在寻找如何嵌套以下代码以检索以下查询中第二个最近的日期:

**Where pet.endtime < (Select max(pet.endtime) From dbo.plannedeventtimeline)**




SELECT Cast(planned.LOCALDAY AS DATE) [Day]
   , actual.Campaign
   , org.Name Organization
   , eAM.EMPLOYEENUMBER SalesID
   , p.LastName + ', ' + p.FirstName Employee
   , DateAdd(HH, planned.tz_offset, planned.min_starttime) PlannedStart
    , DateAdd(HH, planned.tz_offset, actual.min_StartTime) ActualStart
   ,DateAdd(HH, planned.tz_offset, planned.max_endtime) PlannedEnd 
   , DateAdd(HH, planned.tz_offset, actual.max_EndTime) ActualEnd
FROM (
   SELECT orgDay.LOCALDAY
         , pet.WORKRESOURCEID
         , orgDay.ORGANIZATIONID
         , min(pet.Starttime) min_StartTime
         , max(pet.Endtime) max_EndTime     ---This is what I have trouble with---
         , DateDiff(HH, orgDay.StartTime, orgDay.LocalDay) tz_offset
   FROM dbo.PLANNEDEVENTTIMELINE pet
   INNER JOIN dbo.organizationday orgDay
         ON orgDay.ID = pet.ORGANIZATIONDAYID
   WHERE orgDay.LocalDay = CAST(DateAdd(DAY, -1, GETDATE()) as DATE)
   GROUP BY orgday.localday
         , orgday.starttime
         , pet.WORKRESOURCEID
         , orgDay.ORGANIZATIONID
   ) planned
INNER JOIN (
   SELECT spDay.Localday
         , c.Name Campaign
         , aet.EmployeeID
         , min(aet.starttime) min_StartTime
         , max(aet.endtime) max_endtime
   FROM dbo.ACTUALEVENTTIMELINE aet
   LEFT JOIN dbo.ORGANIZATIONDAY spDay
         ON spDay.ID = aet.SPDAYID AND aet.ISPAID != 0
   INNER JOIN dbo.sp sp
         ON sp.sid = spday.SPID
   INNER JOIN dbo.campaign c
         ON c.id = sp.CAMPAIGNID
   WHERE spDay.LocalDay = CAST(DateAdd(DAY, -1, GETDATE()) as DATE)
   GROUP BY spday.localday
         , c.name
         , aet.EMPLOYEEID
   ) AS actual
   ON planned.LOCALDAY = actual.LOCALDAY AND planned.WORKRESOURCEID = actual.EMPLOYEEID
INNER JOIN dbo.ORGANIZATION org
   ON org.id = planned.ORGANIZATIONID
   AND org.Name LIKE '%CPO%'
INNER JOIN dbo.EMPLOYEEAM eam
   ON eam.id = planned.WORKRESOURCEID
INNER JOIN dbo.person p
   ON p.id = eam.personid
ORDER BY 1, 2, 3, 5

2 个答案:

答案 0 :(得分:0)

可以请您替换一下线路吗?

 MAX(pet.Endtime) max_EndTime

使用-

(
    SELECT MAX(Endtime) 
    FROM PLANNEDEVENTTIMELINE 
    WHERE Endtime < max(pet.Endtime)
) max_EndTime

答案 1 :(得分:0)

考虑这种多重CTE解决方案,其中 planned actual 派生表成为CTE,并且新语句 date_ranks 包含一个{{1} }具有ROWNUMBER()PARITION BY的窗口函数。分区列镜像 planned 中的ORDER BY列,以对同一分组中的订单日期进行排名。

然后,在顶级主查询中,使用 date_ranks 在同一GROUP BY列上运行INNER JOIN,仅选择 rank =2。< / p>

GROUP BY