带窗口函数的高级 SQL
Posted
技术标签:
【中文标题】带窗口函数的高级 SQL【英文标题】:Advanced SQL with window function 【发布时间】:2020-03-06 04:24:54 【问题描述】:我有表 a(维度表)和表 B(事实表)存储交易购物者历史记录。
表 a :为唯一组合创建的购物 id(代理键)(第 2 列、第 3 列、第 4 列中的任何重复都将具有相同的购物者 id)
表b是交易数据。
我正在尝试确定每周的新客户和重复客户,预期输出如下。
我正在考虑遵循 SQL 语句
选择 COUNT(*) OVER (PARTITION BY shopperid,weekdate) 作为重复客户的 total_new_shopperid, 为了在相同的加入条件下识别新客户(即唯一),我被困在窗口功能上..
谢谢,
山姆
【问题讨论】:
如果有人在第一周购买了两次,他们算不算两次? 戈登,如果有人购买两次,将被视为一次 【参考方案1】:您可以将DENSE_RANK
解析函数与聚合函数一起使用,如下所示:
SELECT WEEK_DATE,
COUNT(DISTINCT CASE WHEN DR = 1 THEN SHOPPER_ID END) AS TOTAL_NEW_CUSTOMER,
SUM(CASE WHEN DR = 1 THEN AMOUNT END) AS TOTAL_NEW_CUSTOMER_AMT,
COUNT(DISTINCT CASE WHEN DR > 1 THEN SHOPPER_ID END) AS TOTAL_REPEATED_CUSTOMER,
SUM(CASE WHEN DR > 1 THEN AMOUNT END) AS TOTAL_REPEATED_CUSTOMER_AMT
FROM
(
select T.*,
DENSE_RANK() OVER (PARTITION BY SHOPPER_ID ORDER BY WEEK_DATE) AS DR
FROM YOUR_TABLE T);
GROUP BY WEEK_DATE;
干杯!!
【讨论】:
非常感谢,我今天试试执行【参考方案2】:Tejash 的回答很好(我赞成)。
但是,Oracle 在聚合方面非常高效,因此两个级别的聚合可能具有更好的性能(取决于数据):
select week_date,
sum(case when min_week_date = week_date then 1 else 0 end) as new_shoppers,
sum(case when min_week_date = week_date then amount else 0 end) as new_shopper_amount,
sum(case when min_week_date > week_date then 1 else 0 end) as returning_shoppers,
sum(case when min_week_date > week_date then amount else 0 end) as returning_amount
from (select shopper_id, week_date,
sum(amount) as amount,
min(week_date) over (partition by shopper_id) as min_week_date
from t
group by shopper_id, week_date
) sw
group by week_date
order by week_date;
注意:如果这有更好的性能,可能是由于消除了count(distinct)
。
【讨论】:
非常感谢,让我试试这个选项以上是关于带窗口函数的高级 SQL的主要内容,如果未能解决你的问题,请参考以下文章