0

My data is something looked like this

id,submission_state,outcome_state,company_id,office_id,date_created,location_city,location_state,location_country,work_type,is_foreign
op_01CB7TX0DS8AQYKWNZ0AQ80CAY,WILL_SUBMIT,UNKNOWN,co_01CB7TWTZJ73X1V7Y018FPM7PM,of_01CB7TWTZJ73X1V7Y018FPM7PN,2017-07-21T05:56:47.122Z,,,,,1
op_01CB7TX0DS8AQYKWNZ0AQ80CAZ,UNDECIDED,UNKNOWN,co_01CB7TX0DS8AQYKWNZ0AQ80CB0,of_01CB7TX0DS8AQYKWNZ0AQ80CB1,2017-08-17T02:42:45.304Z,Houston,TX,US,,1
op_01CB7TX0DS8AQYKWNZ0AQ80CB2,SUBMITTED,UNKNOWN,co_01CB7TWTYSQQR8B1Q7X6BASZE8,of_01CB7TWTYSQQR8B1Q7X6BASZE9,2017-08-18T21:02:31.897Z,Sandy Springs,GA,US,,1

I want to calculate cumulative daily opportunities by the state?

The results should look like this

| day_created        | location_state | opp_count | cumulative_opps_received |
| ------------------- | -------------- | --------- | ------------------------ |
| 2013-12-13 00:00:00 | CA             | 1         | 1                        |
| 2014-05-16 00:00:00 | CA             | 1         | 2                        |
| 2014-08-02 00:00:00 | CA             | 2         | 4                        |
vegetarianCoder
  • 2,762
  • 2
  • 16
  • 27

1 Answers1

1

You can use aggregation and window functions together:

select date_trunc('day', date_created) as day_created,
       location_state,
       count(*) opp_count,
       sum(count(*)) over (partition by location_state order by min(date_created)) as cumulative_opps_received
from t
group by day_created
order by location_state, day_created;

You can divide if you want the percentage:

select date_trunc('day', date_created) as day_created,
       location_state,
       count(*) opp_count,
       sum(count(*)) over (partition by location_state order by min(date_created))  as cumulative_opps_received,
       (sum(count(*)) over (partition by location_state order by min(date_created)) * 1.0 /
        sum(count(*)) over (partition by location_state)
       ) as cumulative_ratio
from t
group by day_created
order by location_state, day_created;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786