繁体   English   中英

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

[英]case statement within group by clause or partition clause

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

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

  • 每个客户的最大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);

暂无
暂无

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

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