I\'m storing a bunch of data in a view (converted MS Access queries to views). Now what I\'m trying to do is write a stored procedure to pull data based on when the data was add
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