SQL根据不同的列递增值

时间:2018-08-07 20:14:01

标签: sql sql-server

表1看起来像这样:

Name             Date         Hours    HoursType   

Doe, John        8/7/18       22        A
Doe, John        8/7/18       10        B
Doe, John        8/7/18       5         C
Doe, Jane        8/7/18       15        A
Doe, Jane        8/7/18       40        B

我想要一个Select,它将一个递增的整数添加为附加列 理想情况下,它将产生如下结果:

Doe, John        8/7/18       22        A     1
Doe, John        8/7/18       10        B     2
Doe, John        8/7/18       5         C     3
Doe, Jane        8/7/18       15        A     1
Doe, Jane        8/7/18       40        B     2

Doe,John的每一行的第5列应从1开始并以1递增。 它应该从1开始重新命名。

谢谢

3 个答案:

答案 0 :(得分:2)

使用ROW_NUMBER。这是为此而做的。 https://docs.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql?view=sql-server-2017

不确定如何对行进行排序,因为在示例中无法确定顺序,而是选择对实际数据有意义的东西。

select *
    , YourNewColumn = ROW_NUMBER() over(partition by Name order by HoursType)
from YourTable

答案 1 :(得分:0)

SQL表是无序的,并且值没有明显的排序。您问题的答案是row_number(),但带有一些排序列或表达式。例如:

select t.*,
       row_number() over (partition by name order by (select null)) as hourstype
from t;

请注意,将以任意顺序枚举行。如果有用于排序的列,请使用该列代替(select null)

答案 2 :(得分:0)

您可以在SSMS中运行它:

DECLARE @data TABLE( [Name] VARCHAR(50), [Date] DATETIME, [Hours] INT, [HoursType] VARCHAR(1) );

INSERT INTO @data ( [Name], [Date], [Hours], [HoursType] ) VALUES
( 'Doe, John', '8/7/18', 22, 'A' )
, ( 'Doe, John', '8/7/18', 10, 'B' )
, ( 'Doe, John', '8/7/18', 5, 'C' )
, ( 'Doe, Jane', '8/7/18', 15, 'A' )
, ( 'Doe, Jane', '8/7/18', 40, 'B' );

SELECT
    [Name]
    , [Date]
    , [Hours]
    , [HoursType]
    , ROW_NUMBER() OVER ( PARTITION BY [Name] ORDER BY [Name], [Date], [HoursType] ) AS RowNo
FROM @data
ORDER BY
    [Name], [Date], [HoursType];

返回

+-----------+-------------------------+-------+-----------+-------+
|   Name    |          Date           | Hours | HoursType | RowNo |
+-----------+-------------------------+-------+-----------+-------+
| Doe, Jane | 2018-08-07 00:00:00.000 |    15 | A         |     1 |
| Doe, Jane | 2018-08-07 00:00:00.000 |    40 | B         |     2 |
| Doe, John | 2018-08-07 00:00:00.000 |    22 | A         |     1 |
| Doe, John | 2018-08-07 00:00:00.000 |    10 | B         |     2 |
| Doe, John | 2018-08-07 00:00:00.000 |     5 | C         |     3 |
+-----------+-------------------------+-------+-----------+-------+