简体   繁体   English

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

[英]case statement with in group by clause or partition by

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

For a given customer ID, 对于给定的客户ID,

case 1:If the decision is Approved,then retain all the approved records for that customer and drop others. 情况1:如果该决定被批准,则保留该客户的所有批准记录,并删除其他记录。

Case 2: If the customer doesn't have any Approved decision then ,retain the records of particular customer based on latest "req_date" and records within 5 days of this most recent "req_date" and pick the record based on the lowest salary 情况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

The rows have to be filtered in three steps. 行必须分三个步骤进行过滤。 I would use a cte for calculating aggregates and a union of two queries for approved and not approved customers: 我将使用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. DbFiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM