包含in group by子句或partition by的case语句

时间:2018-08-13 23:36:04

标签: sql

Customer   Decision      req_date       salary
   A       Approved     2017-06-13       1000
   A       Approved     2017-06-13       1000
   A       Pending      2017-06-13       500
   B       Pending      2017-10-23       800     
   B       final_stage  2017-10-20       400
   B       final_stage  2017-03-19       400

对于给定的客户ID,

情况1:如果批准了该决定,则保留该客户的所有已批准记录,然后删除其他记录。

情况2:如果客户没有任何批准的决定,则根据最新的“ req_date”保留特定客户的记录,并在最近的“ req_date”的5天内保留记录,并根据最低的记录进行选择工资

Customer   Decision      req_date       salary  
   A       Approved     2017-06-13       1000
   A       Approved     2017-05-13       1000
   B       final_stage  2017-10-20       400

1 个答案:

答案 0 :(得分:1)

必须分三步对行进行过滤。我将使用cte来计算聚合,并为已批准和未批准的客户使用两个查询的并集:

with cte as (
    select 
        customer, 
        bool_or(decision = 'Approved') as approved, 
        max(req_date) as last_date
    from my_table
    group by 1
)
select customer, decision, req_date, salary
from my_table
join cte using(customer)
where approved and decision = 'Approved'
union all (
    select distinct on(customer) customer, decision, req_date, salary
    from my_table
    join cte using(customer)
    where not approved 
    and req_date between last_date- '5day'::interval and last_date
    order by customer, salary
    )

DbFiddle.