【问题标题】:SQL first value by groupSQL 按组的第一个值
【发布时间】:2019-12-19 16:23:50
【问题描述】:

在这样的表中

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 和余额的第一个值 - 如果approved_amount 为空,则在acc_id 处平衡time = min(time)。

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

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;

但仍然不是预期的结果。有人可以帮忙吗?

【问题讨论】:

  • 我的意思是balance 的值,其中time = min(time) 的值是acc_id。因此,第一个帐户是 500,第二个帐户是 800。

标签: sql oracle group-by create-table


【解决方案1】:

您可以使用first_value()窗口函数和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

【讨论】:

    猜你喜欢
    • 2020-05-04
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多