小编典典

group by子句或partition子句中的case语句

sql

Customer   Decision      req_date      dept        salary
   A       Approved     2017-06-13      IT          1000
   A       Approved     2017-06-13      Sales       1000
   A       Pending      2017-06-13      IT          500
   B       Pending      2017-10-23      IT          800     
   B       final_stage  2017-10-20      Sales       400
   B       final_stage  2017-03-19      Sales       400
   B       final_stage  2017-03-20      Marketing   300
   B       pending      2017-10-20      Marketing   400
   B       Pending      2017-04-23      HR          800

对于给定的客户ID,

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

情况2:如果客户没有任何批准的决定,则根据最新的“ req_date”保留特定客户的记录,并在最近的“
req_date”的5天内保留记录,并根据唯一记录中的最低工资来选择记录部门(部门)。

Customer   Decision      req_date      dept        salary
   A       Approved     2017-06-13      IT          1000
   A       Approved     2017-06-13      Sales       1000
   B       Pending      2017-10-23      IT          800     
   B       final_stage  2017-10-20      Sales       400
   B       pending      2017-10-20      Marketing   400

阅读 164

收藏
2021-04-22

共1个答案

小编典典

这种逻辑非常复杂。计算如下:

  • req_date每个客户的最大值。
  • 客户批准的总数。
  • 按客户和部门按工资的序号。

然后将这些与逻辑结合以实现所需的功能:

select t.*
from (select t.*,
             row_number() over (partition by customer, dept order by salary asc) as seqnum
      from (select t.*,
                   max(req_date) over (partition by customer) as max_req_date,
                   count(*) filter (where decision = 'Approved') over (partition by customer) as num_approved
            from t
           ) t
      where decision = 'Approved' or
            req_date >= max_req_date - interval '5 day'
     ) t
where decision = 'Approved' or
      (num_approved = 0 and seqnum = 1);
2021-04-22