将特定的计数器列添加到SQL Server结果

时间:2018-10-23 16:49:51

标签: sql sql-server tsql

我在SQL Server中有一个这样的表:

Name | age
-----+-------
A    |   24
B    |   32
C    |   25
D    |   32
F    |   24
G    |   32
H    |   45
...

如何添加一列重复n次然后递增1的列

示例:(n = 3)

New Column |  Name | age
-----------+-------+-------
1          |   A   |    24
1          |   B   |    32
1          |   C   |    25
2          |   D   |    32
2          |   F   |    24
2          |   G   |    32
3          |   H   |    45
...

谢谢。

4 个答案:

答案 0 :(得分:2)

我只会在row_number()上使用算术:

select (row_number() over (order by name) + 2) / 3 as new_column,
       t.*
from t;

答案 1 :(得分:1)

这建议我LOCATIONSQLiteDatabaseHandler

onCreate()

答案 2 :(得分:1)

另一个选择

示例

Select NewCol = sum(case when RN=1 then 1 end) over (Order by Name)
      ,Name
      ,Age
 From (
        Select *,RN = Row_Number() over (Order by [Name]) % 3
         from @YourTable
      ) A

返回

NewCol  Name    Age
1       A       24
1       B       32
1       C       25
2       D       32
2       F       24
2       G       32
3       H       45

答案 3 :(得分:0)

这是另一种选择。只需使用ROW_NUMBER和一些数学即可。这是示例代码,您可以在其中基于变量定义/更改希望其重复的次数。

DECLARE @TestData TABLE
    (
        [Name] NVARCHAR(2)
      , [Age] INT
    );


--Set your repeating amount here
DECLARE @Repeat INT = 3;

INSERT INTO @TestData (
                          [Name]
                        , [Age]
                      )
VALUES ( 'A', 24 )
     , ( 'B', 32 )
     , ( 'C', 25 )
     , ( 'D', 32 )
     , ( 'F', 24 )
     , ( 'G', 32 )
     , ( 'H', 45 )
     , ( 'I', 22 )
     , ( 'J', 22 )
     , ( 'K', 22 )
     , ( 'L', 22 )
     , ( 'M', 22 )
     , ( 'N', 22 );

SELECT   ( ROW_NUMBER() OVER ( ORDER BY [Name] ) + ( @Repeat - 1 )) / @Repeat AS [New Column]
       , *
FROM     @TestData
ORDER BY [Name];