[英]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
對於給定的客戶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
行必須分三個步驟進行過濾。 我將使用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
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.