在 DB2 数据库中,我有 2 个表
attribute
---------
attribute_id name
1002 xyz
1012 abc
1023 lmn
1057 def
1076 qwe
storecatattrrel
---------------
store_id category_id attribute_id
100 10007 1012
100 10007 1057
100 10007 1023
101 10005 1002
101 10006 1002
101 10007 1057
101 10007 1002
101 10007 1023
101 10007 1076
我正在尝试创建一个SQL查询,我想使用它根据属性名称的字母顺序为类别-存储-属性关系中的属性分配序列值,如下所示。
store_id category_id attribute_id sequence
100 10007 1012 1
100 10007 1057 2
100 10007 1023 3
101 10005 1002 1
101 10006 1002 1
101 10007 1057 1
101 10007 1002 4
101 10007 1023 2
101 10007 1076 3
我尝试使用ROW_NUMBER功能,但没有任何运气。
select b.store_id, b.category_id, b.attribute, a.name, ROW_NUMBER() OVER(partition by attribute_id) from storecatattrrel b
inner join attribute a on a.attribute_id = b.attribute_id
order by name asc;
我找不到一种方法来根据store_id、category_id和attribute_id对结果进行分组,然后分配序列。
任何帮助将不胜感激!
您缺少order by
,需要修复partition by
:
select sc.store_id, sc.category_id, sc.attribute, a.name,
row_number() over (partition by sc.store_id, sc.category_id
order by a.name
) as sequence
from storecatattrrel sc join
attribute a
on a.attribute_id = sc.attribute_id
order by a.name asc;
您的查询是正确的,只是在生成Row_number()
partition by
后缺少order by
子句。有关这方面的更多信息,您可以找到此链接Row_number((
select b.store_id, b.category_id, b.attribute, a.name,
ROW_NUMBER() OVER(partition by b.category_id order by a.name) as Slno from storecatattrrel b
inner join attribute a on a.attribute_id = b.attribute_id