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

时间:2018-08-14 01:32:20

标签: 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

1 个答案:

答案 0 :(得分: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);