小编典典

SELECT语句中的SQL UPDATE在分区语句之上

sql

有我的问题,我有一个像这样的表:

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的方法

我没有找到任何答案可以解决这种问题。如果有人可以给我任何有关是否可行的建议,我将不胜感激。

谢谢!


阅读 195

收藏
2021-03-23

共1个答案

小编典典

您可以加入 子查询 并执行 UPDATE

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子句中添加所需的条件。

2021-03-23