如何调整T-SQL中ROW_NUMBER的分区规则,合并特定前置日期记录?
Solution for Merging Specific Record Partitions in ROW_NUMBER()
Got it, let's break down how to solve this problem. The core requirement is to merge the partition of the Code=674 and Type=P "leading date" record with all subsequent records of the same Serial, while leaving other records' partitioning logic untouched.
Step-by-Step Explanation
- Identify the Base Date: First, we need to find the earliest date of the target record (
Code=674 AND Type='P') for each Serial. This will be our "base date" that we use to merge partitions. - Adjust Partition Date: For each record, if it belongs to a Serial that has this base date, and the record's date is on or after the base date, we use the base date instead of the original
Start_Datefor partitioning. For all other records, we keep the originalStart_Date. - Compute New Sqn: Use
ROW_NUMBER()with the adjusted partition key to generate the sequential numbering we need.
Complete SQL Code
WITH adjusted_partitions AS ( SELECT ID, Start_Date, Code, Serial, Type, Sqn AS Original_Sqn, -- Get the earliest date of Code=674 and Type=P records for each Serial MIN(CASE WHEN Code = 674 AND Type = 'P' THEN Start_Date END) OVER (PARTITION BY Serial) AS base_merge_date FROM your_table_name ) SELECT ID, Start_Date, Code, Serial, Type, ROW_NUMBER() OVER ( PARTITION BY Serial, -- Use base_merge_date for eligible records, else original Start_Date CASE WHEN base_merge_date IS NOT NULL AND Start_Date >= base_merge_date THEN base_merge_date ELSE Start_Date END ORDER BY Type, Original_Sqn ) AS Sqn FROM adjusted_partitions ORDER BY ID, Start_Date, Sqn;
How This Works for Your Sample Data
- ID=03 (Serial=4388): The base_merge_date is
2020-09-23(the only Code=674/Type=P record). All three records fall on or after this date, so they're grouped into the same partition. The ROW_NUMBER orders by Type (P comes first) then Original_Sqn, giving us 1, 2, 3 as expected. - ID=42 (Serial=1316): There are no Code=674 records, so base_merge_date is NULL. The partitioning stays the same as your original logic, so the Sqn values remain unchanged.
- ID=51 (Serial=3210): The base_merge_date is
2020-09-22, which matches all records' Start_Date. They're grouped into one partition, resulting in the sequential Sqn values 1, 2, 3.
Edge Case Handling
- If a Serial has multiple Code=674/Type=P records, this logic uses the earliest one as the base, merging all subsequent records (including later Code=674/Type=P entries) into that partition.
- Records before the base_merge_date (if any exist for the same Serial) will keep their original partitioning.
内容的提问来源于stack exchange,提问作者glass_kites
相关产品推荐
相关产品推荐

