【问题标题】:PostgresSQL: Fill values for null rows based on rows for which we do have valuesPostgresQL:根据我们确实有值的行填充空行的值
【发布时间】:2021-06-27 10:51:14
【问题描述】:

我有下表:

   country year rank
1  Austria 2019    1
2  Austria 2018   NA
3  Austria 2017   NA
4  Austria 2016   NA
5    Spain 2019    2
6    Spain 2018   NA
7    Spain 2017   NA
8    Spain 2016   NA
9  Belgium 2019    3
10 Belgium 2018   NA
11 Belgium 2017   NA
12 Belgium 2016   NA

我想用 2019 年的值(我们有)为每个国家/地区填写 2018 年、2017 年和 2016 年的 NA 值。 我希望输出表如下所示:

   country year rank
1  Austria 2019    1
2  Austria 2018    1
3  Austria 2017    1
4  Austria 2016    1
5    Spain 2019    2
6    Spain 2018    2
7    Spain 2017    2
8    Spain 2016    2
9  Belgium 2019    3
10 Belgium 2018    3
11 Belgium 2017    3
12 Belgium 2016    3

我不知道从哪里开始回答这个问题。我通常使用 R,但现在正在使用 postgresSQL 的平台上工作。我可以在 R 中执行此操作,但认为值得弄清楚它是如何使用 postgres 完成的。

对此的任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    使用更新加入来查找每个国家/地区的非NULL 排名值:

    UPDATE yourTable AS t1
    SET "rank" = t2.max_rank
    FROM
    (
        SELECT country, MAX("rank") AS max_rank
        FROM yourTable
        GROUP BY country
    ) t2
    WHERE t2.country = t1.country;
    -- AND year IN (2016, 2017, 2018)
    

    如果您真的只想定位特定年份,请添加 WHERE 子句的注释掉部分(您的示例似乎暗示您想要回填所有丢失的数据)。

    如果您只想查看输出格式的数据,请使用MAX 作为解析函数:

    SELECT country, year, MAX("rank") OVER (PARTITION BY country) AS "rank"
    FROM yourTable
    ORDER BY country, year DESC;
    

    【讨论】:

      【解决方案2】:

      如果你只想要输出然后 试试这个,

      with cte as (
      select distinct on (country) * from test 
      order by country, year desc
      )
      select 
      t1.id,t1.country,t1.year,t2.rank 
      from test t1 left join cte t2 on t1.country=t2.country
      

      如果你想更新你的表,那么试试这个:

      with cte as (
      select distinct on (country) * from test 
      order by country, year desc
      )
      update test set rank=cte.rank from cte
      where test.country=cte.country
      

      DEMO

      【讨论】:

      • 我正在寻找更新我的表格。感谢您的回复,成功了!
      • 请注意RANK是保留关键字,您可能需要对其进行转义才能运行上述代码。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 2021-06-12
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      相关资源
      最近更新 更多