SQL 覆盖分组依据中列中的值
SQL Overwrite value in column in group by
假设我有关注 sql-table
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 中执行此操作吗?
您可以使用 window 函数:
select t.*,
coalesce(date, min(date) over (partition by fruit)) as imputed_date
from t;
执行此无分析函数的一种方法是使用相关子查询:
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;
假设我有关注 sql-table
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 中执行此操作吗?
您可以使用 window 函数:
select t.*,
coalesce(date, min(date) over (partition by fruit)) as imputed_date
from t;
执行此无分析函数的一种方法是使用相关子查询:
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;