SQL 服务器:在重复值后附加一个数字以区分行

SQL Server: Appending the duplicate value with a number to differentiate the rows

我正在编写查询以使用来自三个表的 JOIN 检索数据。

在结果中,我的主列 (Col1) 重复如下。

Col1 |Col2  |Col3
-----+------+-------
111  |1     |23
111  |2     |21
112  |1     |11
112  |2     |13
112  |3     |12
113  |1     |4
113  |2     |4
113  |3     |4

我想以这样的方式修改查询,当 Col1 重复时, 我需要一个新列 (Col4) 来识别如下差异,方法是按顺序向 Col1 中的现有值添加一个附加数字。这可能最多为 5,因为我将在 col2 中有五个不同的值。

结果如下。这可能吗

Col1  |Col2  |Col3 |Col4  
------+------+-----+------
111   |1     |23   | 111
111   |2     |21   |1111
112   |1     |11   | 112
112   |2     |13   |1121
112   |3     |12   |1122
113   |1     |4    | 113
113   |2     |4    |1131
113   |3     |4    |1132

我正在尝试检索具有一个主 ID 在结果查询中具有多个条目的数据

这看起来像 concat() 算术:

select t.*,
       concat(col1,
              (case when col2 = 1 then '' else col2 - 1 end)
             ) as col4
from t;

如果您的 col2 值不是连续的,您可以使用 row_number():

获得您想要的结果
select results.*, 
       concat(col1, case when row_number() over (partition by col1 order by col2) = 1 then ''
                         else cast(row_number() over (partition by col1 order by col2) - 1 as char)
                    end) as col4
from results

输出:

col1    col2    col3    col4
111     1       23      111
111     2       23      1111                             
112     1       11      112
112     2       13      1121                             
112     3       12      1122                             
113     1       4       113
113     2       4       1131                             
113     3       4       1132 

Demo on dbfiddle

ROW_NUMBER() 可用于对行进行编号...您只需要处理行号 = 1:

SELECT Col1
     , Col2
     , Col3
     , Col4 = CONCAT(Col1, NULLIF(ROW_NUMBER() OVER (PARTITION BY Col1 ORDER BY Col2) - 1, 0))
FROM t

Demo on db<>fiddle