使用相同列两次的条件过滤行

问题描述

我有一个查询

        select CHANNEL,my_date 
        from table_1 d
        where source_data = 'test_5'
          and my_date < to_date('27/09/2020','DD/MM/YYYY')
          and customer_ID = :param_customer_ID
        order by d.my_date asc;

这将显示一个结果:

enter image description here

我的需要是。具有最后一个my_date的最后一个vale过滤器,按渠道分组。此示例的结果必须如下所示:

enter image description here

仅两行。

我尝试过:

select CHANNEL,my_date 
from table_1 d
where source_data = 'test_5'
  and (my_date < to_date('27/09/2020','DD/MM/YYYY') and my_date = max(my_date))
  and customer_ID = :param_customer_ID
group by CHANNEL,my_date 
order by d.my_date asc;

但是什么也没有,它不起作用,并且给我错误

ORA-00934: función de grupo no permitida aquí
00934. 00000 -  "group function is not allowed here"
*Cause:    
*Action:
Error en la línea: 138,columna: 30

我该怎么办?

致谢

解决方法

在Oracle中,您可以使用聚合:

select channel,max(my_date)
from table_1 d
where source_data = 'test_5' and
      my_date < date '2020-09-27' and
      customer_ID = :param_customer_ID
group by channel;

如果需要更多列,请使用row_number()

select channel,my_date
from (select d.*,row_number() over (partition by channel order by my_date desc) as seqnum
      from table_1 d
      where source_data = 'test_5' and
            my_date < date '2020-09-27' and
            customer_ID = :param_customer_ID
     ) d
where seqnum = 1;