标记为True时,要重置SQL窗口的长度吗?

时间:2019-09-12 22:32:15

标签: python sql if-statement partition

我有一张水电费分类表,每个分类都说明一个月的用电量。我想将12人一组加起来得出年度账单。

变量 bill_cd 表示年度账单的最后一部分。 Data download

    cust_id     kwh    bill_cd
0   3333    1104.388683 ?
1   3333    1498.007305 ?
2   3333    662.044822  ?
3   3333    661.342412  ?
4   3333    494.070683  ?
5   3333    300.147843  ?
6   3333    836.677007  ?
7   3333    864.608037  ?
8   3333    933.232845  ?
9   3333    1191.025358 ?
10  3333    1507.119588 ?
11  3333    1980.653631 BILL
12  3333    2621.387010 ?
13  3333    2552.053789 BILL

问题:可以看出,每个年度账单没有12个细分。在此摘要中,我只想获取第一个年度账单的总和,因为它将包括12个细分受众群,但是由于第二个年度账单仅包含两个细分受众群,所以不希望得到它。

我用python编写了这个查询:

import pandas as pd, pandasql as ps

df = pd.read_csv('so_ex.csv')

q1 = """
select cust_id, kwh, bill_cd,
sum(kwh) over (partition by cust_id
    rows between 11 preceding and current row) as kwh_total,
count(kwh) over (partition by cust_id
    rows between 11 preceding and current row) as bseg_count
from df
"""

ps.sqldf(q1, locals())

结果如下。有没有一种方法可以在传递“ BILL”实例后使计数变量重置,以使帐单段计数变为1。这样,我可以稍后在bseg_count = 12处过滤表。

   cust_id      kwh   bill_cd  kwh_total bseg_count
0   3333    1104.388683 ?   1104.388683   1
1   3333    1498.007305 ?   2602.395988   2
2   3333    662.044822  ?   3264.440810   3
3   3333    661.342412  ?   3925.783223   4
4   3333    494.070683  ?   4419.853906   5
5   3333    300.147843  ?   4720.001748   6
6   3333    836.677007  ?   5556.678755   7
7   3333    864.608037  ?   6421.286792   8
8   3333    933.232845  ?   7354.519638   9
9   3333    1191.025358 ?   8545.544996   10
10  3333    1507.119588 ?   10052.664584  11
11  3333    1980.653631 BILL 12033.318215 12
12  3333    2621.387010 ?    13550.316542 12
13  3333    2552.053789 BILL 14604.363026 12

所需的输出:

   cust_id      kwh   bill_cd  kwh_total bseg_count
0   3333    1104.388683 ?   1104.388683   1
1   3333    1498.007305 ?   2602.395988   2
2   3333    662.044822  ?   3264.440810   3
3   3333    661.342412  ?   3925.783223   4
4   3333    494.070683  ?   4419.853906   5
5   3333    300.147843  ?   4720.001748   6
6   3333    836.677007  ?   5556.678755   7
7   3333    864.608037  ?   6421.286792   8
8   3333    933.232845  ?   7354.519638   9
9   3333    1191.025358 ?   8545.544996   10
10  3333    1507.119588 ?   10052.664584  11
11  3333    1980.653631 BILL 12033.318215 12
12  3333    2621.387010 ?    13550.316542 1
13  3333    2552.053789 BILL 14604.363026 2

1 个答案:

答案 0 :(得分:0)

您可以反过来对Three Little Pigs 进行累加计数以定义组,然后使用BILL

row_number()

这些窗口函数应基于排序列(例如日期或顺序ID)。目前尚不清楚该列是什么。