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

DB2筛选数据行并获取字符串排序后的最新条目

Solution for Duplicate (Nr, Key) Group Handling

First, let's recap your requirements clearly:

  • When a combination of Nr and Key appears multiple times:
    • Append ".." to the Nr value
    • Only keep the lexicographically largest (latest when sorted) String value from the group
  • When the combination is unique:
    • Keep the original Nr, Key, and String values as-is

Input Table (TableA)

NrKeyString
11test
11zert
23teuz
24asf
35hgf
35zzzz

Expected Output

NrKeyString
1..1zert
23teuz
24asf
3..5zzzz

Complete SQL Query

WITH tmp AS (
    SELECT 
        Nr,
        Key,
        COUNT(*) AS occurrence_count,
        MAX(String) AS latest_sorted_string
    FROM TableA
    GROUP BY Nr, Key
)
SELECT 
    CASE 
        WHEN occurrence_count > 1 THEN CONCAT(CAST(Nr AS VARCHAR), '..') 
        ELSE CAST(Nr AS VARCHAR) 
    END AS Nr,
    Key,
    latest_sorted_string AS String
FROM tmp;

How This Works

  1. CTE (tmp):

    • Groups the data by Nr and Key to identify duplicate combinations
    • COUNT(*) tracks how many times each (Nr, Key) pair appears
    • MAX(String) grabs the lexicographically largest string from each group (which matches your requirement of keeping the "latest sorted value")
  2. Main Query:

    • Uses a CASE statement to append ".." to Nr only if the pair has multiple occurrences
    • Casts Nr to a string type first to safely concatenate the suffix
    • Selects the original Key and the precomputed latest string from the CTE

This approach efficiently handles both unique and duplicate groups in a single pass over the data, ensuring your expected output is generated correctly.

内容的提问来源于stack exchange,提问作者Viking

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:01:16