Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在组中添加顺序并标记行是否为其组中的最后一行_Sql_Sql Server - Fatal编程技术网

Sql 在组中添加顺序并标记行是否为其组中的最后一行

Sql 在组中添加顺序并标记行是否为其组中的最后一行,sql,sql-server,Sql,Sql Server,我在SQL Server数据库中有一个表,格式如下,按照id排序 id group 1 10 17 10 24 10 2 20 16 20 72 20 104 20 8 30 9 30 我想选择根据行组分组的每一行,并将以下信息添加到此表中:组内的顺序(按排序)以及该行是否为组中的最后一行。换言之,类似于此: id group order last 1 10 1 0

我在SQL Server数据库中有一个表,格式如下,按照
id
排序

id     group
1      10
17     10
24     10
2      20
16     20
72     20
104    20
8      30
9      30
我想选择根据行
分组的每一行,并将以下信息添加到此表中:组内的顺序(按排序)以及该行是否为组中的最后一行。换言之,类似于此:

id     group   order  last
1      10      1      0
17     10      2      0
24     10      3      1
2      20      1      0
16     20      2      0
72     20      3      0
104    20      4      1
8      30      1      0
9      30      2      1

我试过摆弄
行号
,但我对SQL Server没有太多经验,无法让它工作。有人有什么建议吗?

使用
行号
窗口功能

select id,[group],
       row_number()over(partition by [group] order by id) as [order],
       case when row_number()over(partition by [group] order by id desc) = 1 then 1 else 0 end as Last
From yourtable