在分区语句的SELECT排名中的SQL UPDATE

时间:2015-02-20 09:04:32

标签: sql oracle sql-update window-functions

有我的问题,我有一张这样的表:

Company, direction, type, year, month, value, rank

当我创建表时,默认排名为0,我想要的是使用此选择更新表中的排名:

SELECT company, direction, type, year, month, value, rank() OVER (PARTITION BY direction, type, year, month ORDER BY value DESC) as rank
FROM table1
GROUP BY company, direction, type, year, month, value
ORDER BY company, direction, type, year, month, value;

此Select工作正常,但我找不到使用它来更新table1的方法

我没有找到任何解决这类问题的答案。如果有人能给我任何关于它是否可行的建议,我将非常感激。

谢谢!

2 个答案:

答案 0 :(得分:3)

您可以加入子查询并执行更新

UPDATE table_name t2
SET t2.rank=
  SELECT t1.rank FROM(
  SELECT company,
    direction,
    type,
    YEAR,
    MONTH,
    value,
    rank() OVER (PARTITION BY direction, type, YEAR, MONTH ORDER BY value DESC) AS rank
  FROM table_name
  GROUP BY company,
    direction,
    TYPE,
    YEAR,
    MONTH,
    VALUE
  ORDER BY company,
    direction,
    TYPE,
    YEAR,
    MONTH,
    VALUE
  ) t1
WHERE t1.company = t2.company
AND t1.direction = t2.direction;

为谓词添加所需条件。

或者,

您可以使用 MERGE 并将该查询保留在 USING 子句中:

MERGE INTO table_name t USING
(SELECT company,
  direction,
  TYPE,
  YEAR,
  MONTH,
  VALUE,
  rank() OVER (PARTITION BY direction, TYPE, YEAR, MONTH ORDER BY VALUE DESC) AS rank
FROM table1
GROUP BY company,
  direction,
  TYPE,
  YEAR,
  MONTH,
  VALUE
ORDER BY company,
  direction,
  TYPE,
  YEAR,
  MONTH,
  VALUE
) s 
ON(t.company = s.company AND t.direction = s.direction)
WHEN MATCHED THEN
  UPDATE SET t.rank = s.rank;

在ON子句中添加所需条件。

答案 1 :(得分:1)

你可以简单地喜欢这个。这不是众所周知的,但您可以在UPDATE

上制作SELECT
UPDATE 
    (SELECT 
        company, direction, TYPE, YEAR, MONTH, VALUE, 
        RANK() OVER (PARTITION BY direction, TYPE, YEAR, MONTH ORDER BY VALUE DESC) AS NEW_RANK
    FROM table1) a
SET RANK = NEW_RANK;