问题描述
我正在努力通过创建一列来增强数据集,该列将允许我跟踪给定公司在给定行中拥有多少活跃季度。如果一家公司在该季度内确认收入,则该公司“活跃”。 我的数据集的每一行代表一个公司一个月的表现。
我已经能够使用WINDOW函数成功创建活动月份的累计金额:
COUNTIF(Revenue IS NOT NULL) OVER
(partition by Company_Name ORDER BY month_end ASC ROWS BETWEEN unbounded preceding and current row) AS cumulative_active_months
我现在正在努力转换我的逻辑以计算季度而不是月份。
这是我的桌子当前样子的粗略想法。
Row Month Month_end Fiscal_Quarter Company_Name Revenue Active month count
----- ------- ------------ ---------------- -------------- --------- --------------------
1 Jul 2016-07-31 FY17-Q2 Foo x,xxx 1
2 Jul 2016-07-31 FY17-Q2 Bar xxx,xxx 1
3 Aug 2016-08-31 FY17-Q2 Foo xx,xxx 2
4 Aug 2016-08-31 FY17-Q2 Bar xxx 2
5 Sep 2016-09-30 FY17-Q2 Foo xx 3
6 Sep 2016-09-30 FY17-Q2 Bar x,xxx 3
7 Oct 2016-10-31 FY17-Q3 Foo xx 4
8 Oct 2016-10-31 FY17-Q3 Bar Null 3
这是理想情况下我希望桌子看起来像的样子。
Row Month Month_end Fiscal_Quarter Company_Name Revenue Active month count Active quarter count
----- ------- ------------ ---------------- -------------- --------- -------------------- ----------------------
1 Jul 2016-07-31 FY17-Q2 Foo x,xxx 1 1
2 Jul 2016-07-31 FY17-Q2 Bar xxx,xxx 1 1
3 Aug 2016-08-31 FY17-Q2 Foo xx,xxx 2 1
4 Aug 2016-08-31 FY17-Q2 Bar xxx 2 1
5 Sep 2016-09-30 FY17-Q2 Foo xx 3 1
6 Sep 2016-09-30 FY17-Q2 Bar x,xxx 3 1
7 Oct 2016-10-31 FY17-Q3 Foo xx 4 2
8 Oct 2016-10-31 FY17-Q3 Bar Null 3 1
解决方法
如果这是活跃月份:
COUNTIF(Revenue IS NOT NULL) OVER (PARTITION BY Company_Name ORDER BY month_end ASC) AS cumulative_active_months
然后这是将使用COUNT(DISTINCT)
的四分之一的相应计数:
COUNT(DISTINCT CASE WHEN Revenue IS NOT NULL THEN Fiscal_Quarter END) OVER (PARTITION BY Company_Name ORDER BY month_end ASC) AS cumulative_active_quarters
不幸的是,BigQuery不支持此功能,因此您可以使用子查询和累积总和:
select t.* except (seqnum),countif(seqnum = 1) over (partition by company_name order by month_end) as cnt
from (select t.*,(case when revenue is not null
then row_number() over (partition by Company_Name,Fiscal_Quarter order by month_end)
else 0
end) as seqnum
from t
) t;
注意:这不算当前季度,直到有收入为止,我认为这是有道理的。