我有一个表,我想在其中更新特定列的值。列值应该是行号。根据列的不同值,我需要更新新创建的列值。
的例子:
INFO_T
表内容:
Name | id
------------
Arijit | 120
Suman | 240
Priyam | 555
Arijit | 456
Suvayu | 110
Priyam | 300
我需要在上面的表INFO_T
中再添加一列,示例如下。我必须使用ROW_NUMBER() OVER
函数,通过它我必须更新SEQ_NO
列。
Name | id | Seq_no
------------------
Arijit | 120 | 1
Suman | 240 | 2
Priyam | 555 | 3
Arijit | 120 | 1
Suvayu | 110 | 4
Priyam | 555 | 3
如何得到上面的结果?
您可以使用dense_rank()
:
select name, id, dense_rank() over (order by minid) as seqno
from (select t.*, min(id) over (partition by name) as minid
from table t
) t;
如果你想用row_number()
:
select t.name, t.id, tt.seqnum
from table t join
(select t.name, row_number() over (order by min(id)) as seqno
from table t
group by t.name
) tt
on t.name = tt.name;
但是,我不知道你为什么要那样做。
SQL FIDDLE DEMO
SELECT Table1.name, Table1.ID, SEQ.Seq_no
FROM
(SELECT name, ROW_NUMBER() OVER(order by name) as Seq_no
FROM (SELECT DISTINCT name FROM Table1) as unique_name ) as SEQ INNER JOIN
Table1 on SEQ.name = Table1.Name
这是MS SQL,但它看起来像Row_Number在Oracle中的功能相同。如果不能执行CTE (WITH)语句,则可以将其作为子查询执行。也许有Oracle SQL经验的人可以使用这个例子并重新编写它。我不能保证结果,因为它们是无序的,但基本上我首先从表中创建一个没有顺序的RowID。这使我能够确保名称的顺序与您的顺序相同(这似乎是插入顺序)。然后,我对其执行子查询,以按顺序获得每个名称的第一个不同实例。然后我回到原来的那张桌子。在SQLFiddle中。
;WITH NoOrderBy AS
(
select Row_Number() OVER(ORDER BY (SELECT 0)) RowID,Name,id
FROM MyTable
),
DistinctNames AS
(
SELECT Row_Number() OVER(ORDER BY RowID) RowID3,Name,RowID,id
FROM
(
SELECT Row_Number() OVER(PARTITION BY NAME ORDER BY RowID) RowID2,Name,RowID,id
FROM NoOrderBy
) a
WHERE RowID2 = 1
)
SELECT mt.Name,di.id,di.RowID3 Seq_no
FROM MyTable mt
INNER JOIN DistinctNames di
ON mt.Name =di.Name