我有一个这样的表,其中包含一个列号Order
FunctionID Name ParentFunctionID OrderNo Enabled ControllerName ActionName
1 Nikhil 0 10 1 nik
2 Sahil 0 20 1 sah
3 With 2 10 1 sah Withsnew
4 User 2 20 1 sah users
5 Pen 2 10 0 sah pend
44 User Summary 2 210 1 sah usersummary
45 Summary 2 230 1 sah summary
46 Hourly 1 231 1 nik hourly
47 Code 1 232 1 nik code
我希望像
这样的表格FunctionID Name ParentFunctionID OrderNo Enabled ControllerName ActionName
1 Nikhil 0 1 1 nik
2 Sahil 0 2 1 sah
3 With 2 1 1 sah Withsnew
4 User 2 2 1 sah users
5 Pen 2 3 0 sah pend
44 User Summary 2 4 1 sah usersummary
45 Summary 2 5 1 sah summary
46 Hourly 1 1 1 nik hourly
47 Code 1 2 1 nik code
答案 0 :(得分:0)
使用 ROWNUM 功能:
SELECT
FunctionID ,
Name ,
ParentFunctionID,
ROWNUM AS ORDER_NO,
Enabled,
ControllerName ,
ActionName
FROM TABLE NAME;
如果您希望根据特定条件重置rownumbers,请使用 PARTITION 以及 ROW_NUMBER AS:
SELECT
FunctionID ,
Name ,
ParentFunctionID,
ROW_NUMBER() OVER (PARTITION BY ParentFunctionID ORDER BY FunctionID ) AS ORDER_NO,
Enabled,
ControllerName ,
ActionName
FROM TABLE NAME;
答案 1 :(得分:0)
您可以使用ROW_NUMBER (Transact-SQL)枚举由ParentFunctionID
排序的FunctionID
分区的行,以获得您想要的结果。
MS SQL Server 2012架构设置:
create table YourTable
(
FunctionID int,
Name varchar(20),
ParentFunctionID int,
OrderNo int,
Enabled bit,
ControllerName varchar(20),
ActionName varchar(20)
)
go
insert into YourTable values
(1 , 'Nikhil ', 0, 10 , 1, 'nik', ' '),
(2 , 'Sahil ', 0, 20 , 1, 'sah', ' '),
(3 , 'With ', 2, 10 , 1, 'sah', 'Withsnew '),
(4 , 'User ', 2, 20 , 1, 'sah', 'users '),
(5 , 'Pen ', 2, 10 , 0, 'sah', 'pend '),
(44, 'User Summary', 2, 210, 1, 'sah', 'usersummary'),
(45, 'Summary ', 2, 230, 1, 'sah', 'summary '),
(46, 'Hourly ', 1, 231, 1, 'nik', 'hourly '),
(47, 'Code ', 1, 232, 1, 'nik', 'code ')
查询1 :
with C as
(
select OrderNo,
row_number() over(partition by ParentFunctionID order by FunctionID) as rn
from YourTable
)
update C
set OrderNo = rn
select *
from YourTable
<强> Results 强>:
| FUNCTIONID | NAME | PARENTFUNCTIONID | ORDERNO | ENABLED | CONTROLLERNAME | ACTIONNAME |
|------------|--------------|------------------|---------|---------|----------------|-------------|
| 1 | Nikhil | 0 | 1 | 1 | nik | |
| 2 | Sahil | 0 | 2 | 1 | sah | |
| 3 | With | 2 | 1 | 1 | sah | Withsnew |
| 4 | User | 2 | 2 | 1 | sah | users |
| 5 | Pen | 2 | 3 | 0 | sah | pend |
| 44 | User Summary | 2 | 4 | 1 | sah | usersummary |
| 45 | Summary | 2 | 5 | 1 | sah | summary |
| 46 | Hourly | 1 | 1 | 1 | nik | hourly |
| 47 | Code | 1 | 2 | 1 | nik | code |
答案 2 :(得分:0)
您可以像使用
一样使用ROW_NUMBER和ParentFunctionID进行分区SELECT FunctionID, Name, ParentFunctionID
, ROW_NUMBER() OVER(PARTITION BY ParentFunctionID ORDER BY FunctionID) OrderNo
, [Enabled], ControllerName, ActionName
FROM TABLENAME
这将返回结果集,如果要更新,可以修改脚本。
我希望这有用。