2011-12-28 62 views
0

我有一个位置列的TO DO表。 (为简单起见除去其它列)重新排序SQL位置列

Description varchar(max) 
Position int 
JobFinished bit 

如果我有n行量,每一个行被添加的位置时被递增。所以值可能是这样的:

Drop Off Kids, 0, 0 
Get Groceries, 1, 0 
Pickup Kids,  2, 0 

现在,如果我做了一些事情,我想从表中删除它。并增加其他所有位置的列,以便他们都是为了从0

也就是说,如果我得到杂货我所需要的值,如下所示:

Drop off Kids, 0, 0 
Get Grocerieis, NULL, 1 
Pickup Kids, 1, 0 

是否与SQL什么办法能做到这一点? (IM使用SQL Server)

+0

类似:http://stackoverflow.com/questions/8607998/using-a-sort-order-column-in-a-database-table/8608085#8608085 – xQbert 2011-12-28 01:45:59

回答

1

这是很简单的SQL问题,请查看您的SQL Server的引用,更新SQL语句:

update todo_table set position = position -1 where position > 1; 
update todo_table set position = NULL, JobFinished = 1 where Description='Get Grocerieis' 
+0

嗨,但这并不总是奏效。如果有10个项目,并且我移除位置8处的项目,然后运行此查询。这将影响所有的项目8.但我已经意识到我可以做更新Tablre设置位置=位置 - 1位置>(位置将被删除)..现在我想起它是一个很简单的。谢谢 – michael 2011-12-28 01:52:14

1

假设负增量是唯一的问题,而不是重新排列而且你有办法“集团”你的套..然后

update toDO set position = position -1 where position > @recordDeletedPosition and GroupingMethod = something

0

虽然它看起来像一个糟糕的设计,你可以尝试用ROW_NUMBER功能该解决方案(SQL即成R 2005 +)

DECLARE @tbl table(i int) 

INSERT INTO @tbl VALUES (0),(null),(2),(null),(null),(5) 

UPDATE n 
SET i=rn-1 
FROM (SELECT i,ROW_NUMBER() OVER(ORDER BY i) rn 
     FROM @tbl 
     WHERE not i is null) n 




SELECT * FROM @tbl 
0
with cte as (
    select Position, row_number() over (order by position) - 1 as NewPosition 
    from tbl 
    where JobFinished = 0 
) 
update tbl 
set Position = NewPosition