关于`LAST_VALUE`日期区间及TableA按Clt_id聚合列的SQL需求问询
Alright, let's tackle this problem for you. You're looking to generate a unique aggregated First_Service_Date2 value per Clt_id in TableA, using date-based logic with LAST_VALUE (and related window functions) around assignment_dt, Start_Date, and End_Date.
First, let's clarify the rule set (I'm assuming there was a minor typo in your original description, since repeating "when End_Date is not null" twice doesn't make logical sense):
- When
End_Dateis not null: Grab the most recentassignment_dtthat falls before the row'sStart_Date - When
End_Dateis null: Grab the nextassignment_dtthat falls after the row'sStart_Date
Here's a step-by-step SQL solution tailored to this requirement:
Step 1: Calculate Window Function Values with a CTE
We'll first compute the necessary date values for each row within the same Clt_id group:
WITH client_service_context AS ( SELECT Clt_id, Start_Date, End_Date, assignment_dt, -- Get the latest assignment_dt before the current Start_Date using LAST_VALUE LAST_VALUE(CASE WHEN assignment_dt < Start_Date THEN assignment_dt END) OVER ( PARTITION BY Clt_id ORDER BY assignment_dt ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS last_prior_assignment, -- Get the next assignment_dt after the current row's assignment_dt LEAD(assignment_dt) OVER (PARTITION BY Clt_id ORDER BY assignment_dt) AS next_assignment FROM TableA )
Step 2: Aggregate to Get Unique First_Service_Date2 per Client
Now we'll group by Clt_id and apply your rules to get a single aggregated value:
SELECT Clt_id, CASE -- If any non-null End_Date exists for the client, use the latest valid prior assignment WHEN MAX(End_Date) IS NOT NULL THEN MAX(last_prior_assignment) -- If all End_Date values are null, use the next assignment date ELSE MAX(next_assignment) END AS First_Service_Date2 FROM client_service_context GROUP BY Clt_id;
Key Details:
PARTITION BY Clt_idensures all calculations are isolated to individual clients- The
LAST_VALUEwith a custom window frame (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) guarantees we only consider assignment dates up to the current row that are earlier thanStart_Date - Using
MAX()in the aggregation step ensures we get a single unique value per client (adjust toMIN()if your edge cases require it)
If your original rule had a different intent (e.g., two separate conditions for non-null End_Date), feel free to clarify and I can tweak the query to match!
内容的提问来源于stack exchange,提问作者John

