SQL 组的第一个值

SQL first value by group

像这样的table

acc_id   time   approved_amount   balance
 11       Jan14     580             500
 11       Feb14     580             400
 11       Mar14     580             300
 11       Apr14     580             200
 22       Jan14     .               800
 22       Feb14     .               700
 22       Mar14     .               600

我想创建一个 orig_amount 列,如果它不为空,它等于 approved_amount 并且等于 balance 的第一个值 - 通过 [= 在 time = min(time) 平衡17=] 如果 approved_amount 为空。

因此,所需的输出将如下所示:

acc_id   time   approved_amount   balance   orig_amount
 11       Jan14     580             500        580
 11       Feb14     580             400        580
 11       Mar14     580             300        580
 11       Apr14     580             200        580
 22       Jan14     .               800        800
 22       Feb14     .               700        800
 22       Mar14     .               600        800

我现在有了这个

create table second_table as
   select *,
      coalesce(approved_amount, case when time = min(time) then 
       balance end ) as orig_amount
   from first_table
   group by acc_id
   order by acc_id, time;

但还是不是想要的结果。有人可以帮忙吗?

您可以使用 first_value() window 函数和 coalesce().

SELECT acc_id,
       time,
       approved_amount,
       balance,
       coalesce(approved_amount,
                first_value(balance) OVER (PARTITION BY acc_id
                                           ORDER BY time)) orig_amount
       FROM first_table;

db<>fiddle