You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于`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_Date is not null: Grab the most recent assignment_dt that falls before the row's Start_Date
  • When End_Date is null: Grab the next assignment_dt that falls after the row's Start_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_id ensures all calculations are isolated to individual clients
  • The LAST_VALUE with 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 than Start_Date
  • Using MAX() in the aggregation step ensures we get a single unique value per client (adjust to MIN() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:00:48