Number rows based on id

时间:2018-12-19 11:32:13

标签: sql-server tsql

I have a query that returns something like this:

Id | Value
1  | Hi,
1  | I'm
2  | just
2  | an
2  | example
3  | message.

What I want to do is number the rows based on the id. So with the example above, I want to return something like this:

Id | Value    | Number
1  | Hi,      | 1
1  | I'm      | 2
2  | just     | 1
2  | an       | 2
2  | example  | 3
3  | message. | 1

Is there a simple way to do this in the same query as the one you would use in the first example?

4 个答案:

答案 0 :(得分:1)

The problem is there is NOTHING in that table that guarantees the order of rows, so the result you want cannot be guaranteed.

select *
   , row_number() over(partition by id order by (select 1)) as Number
from yourtable

答案 1 :(得分:0)

You can make use of the rownumber function.

SELECT ROW_NUMBER OVER (PARTITION BY ID ORDER BY (SELECT 1)) AS RowNumb

答案 2 :(得分:0)

您可以使用ROW_NUMBER()函数和按ID进行分区。像这样

DECLARE @MyTable AS TABLE
(
    Id INT,
    [Value] VARCHAR(50)
)

INSERT INTO @MyTable
(
    Id,
    [Value]
)
SELECT '1','Hi,' UNION
SELECT '1','I''m' UNION
SELECT '2','just' UNION
SELECT '2','an' UNION
SELECT '2','example' UNION
SELECT '3','message.'

SELECT
    *,
    Number = ROW_NUMBER() OVER(PARTITION BY Id ORDER BY Id)
    FROM @MyTable

结果

Id          Value                                              Number
----------- -------------------------------------------------- --------------------
1           Hi,                                                1
1           I'm                                                2
2           an                                                 1
2           example                                            2
2           just                                               3
3           message.                                           1

答案 3 :(得分:0)

请尝试以下脚本。

DECLARE @MyTable AS TABLE
(
    Id INT,
    [Value] VARCHAR(50)
)

INSERT INTO @MyTable
(
    Id,
    [Value]
)
SELECT '1','Hi,' UNION
SELECT '1','I''m' UNION
SELECT '2','just' UNION
SELECT '2','an' UNION
SELECT '2','example' UNION
SELECT '3','message.'

select *, dense_rank()over(partition by Id order by  Value) as Number from @MyTable
/*
Id          Value                                              Number
----------- -------------------------------------------------- --------------------
1           Hi,                                                1
1           I'm                                                2
2           an                                                 1
2           example                                            2
2           just                                               3
3           message.                                           1
*/

最好的问候

瑞秋

相关问题