如何使用ROW_NUMBER()OVER值更新列值,该值基于列的不同值

时间:2015-07-20 12:53:29

标签: sql oracle window-functions row-number

我有一个表,我想在其中更新特定列的值。列值应为行号。基于列的不同值,我需要更新新创建的列值。

示例:

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

如何获得上述结果?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您可以将Private Sub Command0_Click() Dim rst As DAO.Recordset Set rst = CurrentDb.OpenRecordset("SELECT DISTINCT [Portfolio Code], [Trustee 1] FROM [General] ORDER BY [Portfolio Code];", dbOpenSnapshot) Do While Not rst.EOF strRptFilter = "[Portfolio Code] = " & Chr(34) & rst![Portfolio Code] & Chr(34) DoCmd.OutputTo acOutputReport, "Main Report", acFormatPDF, "O:\Annual Review\AnnualReviewReport" & "\" & rst![Trustee 1] & "\" & rst![Portfolio Code] & " - " & rst![Trustee 1] & ".pdf" DoEvents rst.MoveNext Loop rst.Close Set rst = Nothing End Sub 用于此目的:

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()

但是,我不知道你为什么要那样做。

答案 2 :(得分:0)

这是MS SQL,但看起来Row_Number在Oracle中的功能相同。如果您不能执行CTE(WITH)语句,则可以将这些语句作为子查询来完成。也许具有Oracle SQL经验的人可以使用此示例并重新编写它。我不能保证结果,因为它们是无序的,但基本上我首先从表中创建一个没有顺序的RowID。这使我能够确保名称与您拥有的名称相同(这似乎是插入顺序)。然后我基本上做了子查询,以便按顺序获取每个名称的FIRST不同实例。然后我加入了原来的桌子。这是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