2016年的博客文章指出了这个问题,并提供了一个基本的解决方法,因此谢谢Mark D.
Adams。奇怪的是,我在所有的网络上都找不到,因此我正在共享我的(经过测试的)解决方案。
关键的见解是
dense_rank(),按相关商品排序,可以为相同商品提供相同的排名,因此,最高排名也是唯一商品的计数。如果您尝试为我想要的每个分区交换以下内容,那就太糟了:
dense_rank() over(partition by order_month, traffic_channel order by customer_id)
由于您需要最高的排名,因此您必须对所有内容进行子查询,然后从每个获得的排名中选择最大值。 重要的是将外部查询中的分区与子查询中的相应分区进行匹配。
select distinct order_month , traffic_channel , max(tc_mth_rnk) over(partition by order_month, traffic_channel) customers_by_channel_and_month , max(tc_rnk) over(partition by traffic_channel) ytd_customers_by_channel , max(mth_rnk) over(partition by order_month) monthly_customers_all_channels , max(cust_rnk) over() ytd_total_customersfrom ( select order_month , traffic_channel , dense_rank() over(partition by order_month, traffic_channel order by customer_id) tc_mth_rnk , dense_rank() over(partition by traffic_channel order by customer_id) tc_rnk , dense_rank() over(partition by order_month order by customer_id) mth_rnk , dense_rank() over(order by customer_id) cust_rnk from orders_traffic_channels where to_char(order_month, 'YYYY') = '2017' )order by order_month, traffic_channel;
笔记
max()
且dense_rank()
必须匹配的分区dense_rank()
将对null值进行排名(所有排名都在同一排名,即最大值)。如果您不希望对null
值进行计数,则需要一个case when customer_id is not null then dense_rank() ...etc...
,或者,max()
如果您知道存在空值,则可以从中减去一个。



