【问题标题】:SQL Overwrite value in column in group bySQL 覆盖分组中列中的值
【发布时间】:2021-04-13 04:20:27
【问题描述】:

假设我有以下 sql 表

fruit | amount | date
-------------------------
apple |    2   | 2019
apple |    3   | 2018
apple |    2   | 
peach |    2   | 
peach |    3   | 2017

我想用每个水果的最早日期填充日期列中的空值,以便日期列不包含空值。结果应如下所示:

fruit | amount | date
-------------------------
apple |    2   | 2019
apple |    3   | 2018
apple |    2   | 2018
peach |    2   | 2017
peach |    3   | 2017

任何想法如何在 sql 中执行此操作?

【问题讨论】:

    标签: sql aggregation


    【解决方案1】:

    你可以使用窗口函数:

    select t.*,
           coalesce(date, min(date) over (partition by fruit)) as imputed_date
    from t;
    

    【讨论】:

      【解决方案2】:

      无分析函数的一种方法是使用相关子查询:

      SELECT
          fruit,
          amount,
          COALESCE(date, (SELECT MIN(date) FROM yourTable t2 WHERE t2.fruit = t1.fruit)) date
      FROM yourTable t1;
      

      我们还可以使用聚合连接方法:

      SELECT
          t1.fruit,
          t1.amount,
          COALESCE(t1.date, t2.min_date) AS date
      FROM yourTable t1
      INNER JOIN
      (
          SELECT fruit, MIN(date) AS min_date
          FROM yourTable
          GROUP BY fruit
      ) t2
          ON t2.fruit = t1.fruit;
      

      【讨论】:

        猜你喜欢
        • 2017-03-21
        • 1970-01-01
        • 2015-10-02
        • 1970-01-01
        • 1970-01-01
        • 2018-09-03
        • 2018-06-20
        • 2014-08-20
        • 1970-01-01
        相关资源
        最近更新 更多