SQL计算自该月的第一天以来每天的累计Distinct计数

时间:2019-04-01 13:34:46

标签: sql oracle

我有一个表,其中包含日期,细分,区域,省和Billing_nbr行。我还希望根据从该行的日期追溯到该月的第一天(即月至今日期计数),在Billing_nbr where total_revenue > 0 count 个计数。这意味着它应该是从一个月的第一天到观察日期(每行的日期)的所有billing_nbrs的累积计数。这意味着,如果billing_nbr在第一天发生,则即使第二天未发生,也应将其包括在第二天的计数中,但如果在两天都发生,则应将其计数一次。另一个Billing_nbr where total_revenue > 0的正常计数由其他列分组。以下是我的数据:

enter image description here

我有“加入下方”,但在两个方面都给了我相似的数字:

SELECT 
    MAIN_TABLE.*,
    TOT_SUBS_COUNT.N AS A1_SUBSCRIBERS_TOTAL,
    TOT_SUBS_COUNT_MTD.N AS TOTAL_MTD_A1_SUBSCRIBERS
FROM (
        select  
                ddate,
                SUM(TOTAL_REVENUE) AS REVENUE_TOTAL, 
                segment,
                province,
                area
        from CADA_PERMSISDN_DASHBOARD 
        GROUP BY province, area, segment, ddate
        order by ddate
) MAIN_TABLE
JOIN(
    select DDATE, count(DISTINCT BILLING_NBR) AS N, province, area, SEGMENT from CADA_PERMSISDN_DASHBOARD
    WHERE TOTAL_REVENUE > 0
    GROUP BY province, area, segment, ddate
    ORDER BY DDATE
) TOT_SUBS_COUNT ON MAIN_TABLE.DDATE = TOT_SUBS_COUNT.DDATE 
AND MAIN_TABLE.SEGMENT = TOT_SUBS_COUNT.SEGMENT 
AND MAIN_TABLE.PROVINCE = TOT_SUBS_COUNT.PROVINCE 
AND MAIN_TABLE.AREA = TOT_SUBS_COUNT.AREA
JOIN(
    select DDATE, count(DISTINCT BILLING_NBR) AS N, province, area, SEGMENT from CADA_PERMSISDN_DASHBOARD
    WHERE TOTAL_REVENUE > 0
    AND DDATE BETWEEN trunc((DDATE),'month') AND DDATE
    GROUP BY province, area, segment, ddate
    ORDER BY DDATE
) TOT_SUBS_COUNT_MTD ON MAIN_TABLE.DDATE = TOT_SUBS_COUNT_MTD.DDATE 
AND MAIN_TABLE.SEGMENT = TOT_SUBS_COUNT_MTD.SEGMENT
AND MAIN_TABLE.PROVINCE = TOT_SUBS_COUNT_MTD.PROVINCE 
AND MAIN_TABLE.AREA = TOT_SUBS_COUNT_MTD.AREA

第一个联接用于分组计数,第二个联接用于从一个月的第一天到观察日期(即每一行的日期)的累积计数,并且必须由其他联接分组列。计数列分别为别名A1_SUBSCRIBERS_TOTAL和OTAL_MTD_A1_SUBSCRIBERS。以下是我获取的数据,您看不到这两列的计数相同:

enter image description here

2 个答案:

答案 0 :(得分:0)

我不知道您的数据与查询有什么关系。但是对于一个月内的最新金额,您可以使用分析函数,如下所示:

select ddate, segment, province, area,
       sum(total_revenue) as revenue_total,
       sum(sum(total_revenue)) over (partition by trunc(ddate, 'MON') order by ddate) as mtd_revenue_total
from CADA_PERMSISDN_DASHBOARD 
group by province, area, segment, ddate
order by ddate

答案 1 :(得分:0)

SELECT
TO_CHAR(A.ddate, 'YYYY-MM'), 
A.segment, 
A.province, 
A.area,
SUM(CASE WHEN total_revenue > 0 THEN 1 ELSE 0 END) TOTAL_GT_ZERO,
COUNT(*) TOTAL_SUBSCRIBERS
from CADA_PERMSISDN_DASHBOARD A
group by TO_CHAR(A.ddate, 'YYYY-MM'), A.segment, A.province, A.area

据我了解。但是您能提供您所期望的吗?