[英]What is the best way to initialize a SortOrder column (e.g. 0, 1, 2, 3) where there are multiple groups based on another field?
I have a table of list items. 我有一个列表项目表。 There is a ListID column used as an identifier to group the list items together.
有一个ListID列用作标识符,用于将列表项组合在一起。 Is there a sane way to give every item a sort order, starting at 0 per list and incremental by one per item.
是否有一种理智的方式为每个项目提供排序顺序,从每个列表0开始,每个项目增加1。
Basically, I need to populate the following SortOrder Column values for a large number of entries/ListIDs. 基本上,我需要为大量条目/ ListID填充以下SortOrder列值。
ID ListID SortOrder
1 1 0
2 0 0
3 1 1
4 0 1
5 1 2
6 0 2
7 2 0
8 2 1
9 2 2
You can use ROW_NUMBER()
with a PARTITION
on the ListId
field for this: 你可以在
ListId
字段上使用带有PARTITION
ROW_NUMBER()
:
Select Id, ListId,
Row_Number() Over (Partition By ListId Order By Id) -1 As SortOrder
From YourTable
Order By Id
I think you want: 我想你想要:
WITH toupdate as (
SELECT t.*,
ROW_NUMBER() OVER (PARTITION BY ListId Order By id) as new_SortOrder
FROM tableName
)
UPDATE toupdate a
SET sortorder = new_sort_order;
SQL Server has the nice ability to update a subquery or CTE under some circumstances. 在某些情况下,SQL Server具有更新子查询或CTE的能力。
Do you need to persist the order of lists containing items that are shared between lists? 您是否需要保持包含列表之间共享项的列表顺序? If so, perhaps variations on this schema would work for you.
如果是这样,这个模式的变体可能适合您。
Item
id label
1 A
2 B
3 C
4 D
List
id listName
1 abc list
2 cbd list
3 aaa list
ListMembership
id listId itemId order
1 1 1 1
2 1 2 2
3 1 3 3
4 2 2 2
5 2 3 1
6 2 4 3
7 3 1 1
8 3 1 2
9 3 1 3
usage: 用法:
select i.label from listMembership as lm
join Item as i on i.id=lm.itemId
where lm.listId=2
order by lm.order
yields: 收益率:
label
C
B
D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.