SQL Server query assistance needed

Deadly 提交于 2019-12-02 13:05:49

You are using window function, but you are not filtering by it, so whats the point? If you want the earliest and the latest, choose rn = 1 :

Select Name, PlanID, ApptDate, 1stAppt,2ndappt, rn,
from (Select *,
            row_number() over (partition by PlanID Order BY AddedonDate desc) as rn
     from  vClientInfo
     Union All
     Select *, 
           row_number() over (partition by PlanID Order BY AddedonDate asc) as rn 
     from  vClientInfo)
WHERE rn = 1

If you want 1st appt from the earliest and 2ndappt from the latest :

Select Name, PlanID, ApptDate,
       MAX(CASE WHEN rnk = 1 then 1stAppt end) as 1stAppt,
       MAX(CASE WHEN rn = 1 THEN 2ndappt end) as 2ndAppt
from (Select *,
            row_number() over (partition by PlanID Order BY AddedonDate desc) as rn,
     0 as rnk
     from  vClientInfo
     Union All
     Select *,
           0 as rn,
           row_number() over (partition by PlanID Order BY AddedonDate asc) as rnk 
     from  vClientInfo)
GROUP BY Name,PlanID,ApptDate
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!