Home  >  Blog  >   Snowflake  > 

How do we Calculate the Running Total or Cumulative Sum in Snowflake

To calculate the cumulative sum or running table, first, we will create a table that contains a  count column and a day column. Next, we will create the Common Table Expressions and use the “Windows” function for calculating the Running total or Cumulative sum. This blog will discuss creating CTE(Common Table Expressions) and using the “Windows” function.

Rating: 4.5
  
 
247
  1. Share:
Snowflake Articles

Snowflake - Calculate the Running Total or Cumulative Sum

First, we create the table with the day column and the count column:

select
to_date(start_date) as day,
count(2)
from sessions1
group by to_date(start_date);
Day Count
2022-06-03 2
2022-06-04 4
2022-06-05 6

After that, we will write the Snowflake CTE(Common Table Expressions) and utilise the window function for keeping the track of the running total or cumulative sum.

select 
to_date(start_date) as day,
count(2)
from sessions2
group by to_date(start_date);

with data as (
  select
    to_date(start_date) as day,
    count(2) as number_of_sessions
from sessions2
group by to_date(start_date)
)
select
   day,
   sum(number_of_sessions) over (order by day asc rows between unbounded preceding and current row)
from data;

 MindMajix YouTube Channel

Conclusion

By the end of this blog, you can create the Common Table Expressions and use the Windows function for calculating the Running total or Cumulative sum. I hope this information is sufficient.

Snowflake Related Articles


▶  Snowflake vs Redshift
▶  Snowflake vs BigQuery
▶  Snowflake vs Databricks
▶  Snowflake vs Azure
▶  Snowflake vs Hadoop
▶  Snowflake Time Travel

If you have any queries, let us know by commenting below.

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Snowflake TrainingJul 30 to Aug 14
Snowflake TrainingAug 02 to Aug 17
Snowflake TrainingAug 06 to Aug 21
Snowflake TrainingAug 09 to Aug 24
Last updated: 28 July 2022
About Author
SaiKumar Kalla

Kalla Saikumar is a technology expert and is currently working as a content associate at MindMajix. Write articles on multiple platforms such as ServiceNow, Business Analysis, Performance Testing, Mulesoft, Oracle Exadata, Azure, and other courses. And you can join him on LinkedIn.