更新排序与组

时间:2016-01-11 07:33:38

标签: sql sql-server-2008 sorting

如何更改一行的位置以更改顺序 最好用例子来解释

我有以下状态表

Id Name     StatusOrder StatusGroup
1  Open     1           1
2  Start    2           1
3  Load     3           1
4  Close    4           1
5  Begin    1           2
6  Open     2           2
7  Close    3           2

我想从第一组切换状态订单2和3。 跳跃可以超过一行,例如。也可能在同一组中,从开放的订单移至状态订单3

当我按照选择

播种时播种
SELECT * FROM Status WHERE (StatusGroup =1)

结果集:

Id Name     StatusOrder StatusGroup
1  Open     1           1
3  Load     2           1
2  Start    3           1
4  Close    4           1
5  Begin    1           2
6  Open     2           2
7  Close    3           2

我已经找到了以下文章的示例,但我没有成功将其整合,只针对订单更改的一个组 Using a sort order column in a database table

怎么能帮助我?

1 个答案:

答案 0 :(得分:1)

如果正确理解,请转到:

<强> QUERY

create table #t
(
    Id INT,
    Name VARCHAR(20),
    StatusOrder INT,
    StatusGroup INT
)
insert into #t values 
(1  ,'Open',    1 , 1),
(2  ,'Start',   2 , 1),
(3  ,'Load',    3 , 1),
(4  ,'Close',   4 , 1),
(5  ,'Begin',   1 , 2),
(6  ,'Open',    2 , 2),
(7  ,'Close',   3 , 2)

;with cte as (
select *, row_number() over(partition by StatusGroup order by Id) rn 
from #t
)
select case when StatusOrder = 2 then 3 when StatusOrder = 3 then 2 else Id end as Id,
       case when StatusOrder = 2 then 'Load' when StatusOrder = 3 then 'Start' else Name end as Name,
       StatusOrder,
       StatusGroup
from cte 
where rn = id

union all

select Id, Name, StatusOrder, StatusGroup
from cte
where rn <> id

drop table #t

<强>输出

Id  Name    StatusOrder StatusGroup
1   Open    1           1
3   Load    2           1
2   Start   3           1
4   Close   4           1
5   Begin   1           2
6   Open    2           2
7   Close   3           2

<强>更新

因此,如果您有需要更新记录的表,您可以执行以下操作:

;with cte as (
select *, row_number() over(partition by StatusGroup order by Id) rn 
from #t
)
update t
set t.Id = (case when cte.StatusOrder = 2 then 3 
               when cte.StatusOrder = 3 then 2 else t.Id end),
    t.Name = (case when cte.StatusOrder = 2 then 'Load' 
                   when cte.StatusOrder = 3 then 'Start'  else t.Name end)
from cte
join #t t on cte.id = t.id
where cte.rn = cte.id