DB2筛选数据行并获取字符串排序后的最新条目
Solution for Duplicate (Nr, Key) Group Handling
First, let's recap your requirements clearly:
- When a combination of
NrandKeyappears multiple times:- Append
".."to theNrvalue - Only keep the lexicographically largest (latest when sorted)
Stringvalue from the group
- Append
- When the combination is unique:
- Keep the original
Nr,Key, andStringvalues as-is
- Keep the original
Input Table (TableA)
| Nr | Key | String |
|---|---|---|
| 1 | 1 | test |
| 1 | 1 | zert |
| 2 | 3 | teuz |
| 2 | 4 | asf |
| 3 | 5 | hgf |
| 3 | 5 | zzzz |
Expected Output
| Nr | Key | String |
|---|---|---|
| 1.. | 1 | zert |
| 2 | 3 | teuz |
| 2 | 4 | asf |
| 3.. | 5 | zzzz |
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
CTE (
tmp):- Groups the data by
NrandKeyto identify duplicate combinations COUNT(*)tracks how many times each (Nr, Key) pair appearsMAX(String)grabs the lexicographically largest string from each group (which matches your requirement of keeping the "latest sorted value")
- Groups the data by
Main Query:
- Uses a
CASEstatement to append".."toNronly if the pair has multiple occurrences - Casts
Nrto a string type first to safely concatenate the suffix - Selects the original
Keyand the precomputed latest string from the CTE
- Uses a
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
相关产品推荐
相关产品推荐

