SQL UPDATE in a SELECT rank over Partition sentence

后端 未结 2 828
渐次进展
渐次进展 2021-01-07 05:35

There is my problem, I have a table like this:

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

When I create the table, rank is 0 by def

相关标签:
2条回答
  • 2021-01-07 06:19

    You could join the sub-query and do an 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;
    

    Add required conditions to the predicate.

    Or,

    You could use MERGE and keep that query in the USING clause:

    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;
    

    Add required conditions in the ON clause.

    0 讨论(0)
  • 2021-01-07 06:32

    You can to it simply like this. It is not that commonly known but you can make UPDATE on a 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;
    
    0 讨论(0)
提交回复
热议问题