Book Image

SQL for Data Analytics - Third Edition

By : Jun Shan, Matt Goldwasser, Upom Malik, Benjamin Johnston
Book Image

SQL for Data Analytics - Third Edition

By: Jun Shan, Matt Goldwasser, Upom Malik, Benjamin Johnston

Overview of this book

Every day, businesses operate around the clock, and a huge amount of data is generated at a rapid pace. This book helps you analyze this data and identify key patterns and behaviors that can help you and your business understand your customers at a deep, fundamental level. SQL for Data Analytics, Third Edition is a great way to get started with data analysis, showing how to effectively sort and process information from raw data, even without any prior experience. You will begin by learning how to form hypotheses and generate descriptive statistics that can provide key insights into your existing data. As you progress, you will learn how to write SQL queries to aggregate, calculate, and combine SQL data from sources outside of your current dataset. You will also discover how to work with advanced data types, like JSON. By exploring advanced techniques, such as geospatial analysis and text analysis, you will be able to understand your business at a deeper level. Finally, the book lets you in on the secret to getting information faster and more effectively by using advanced techniques like profiling and automation. By the end of this book, you will be proficient in the efficient application of SQL techniques in everyday business scenarios and looking at data with the critical eye of analytics professional.
Table of Contents (11 chapters)
9
9. Using SQL to Uncover the Truth: A Case Study

5. Window Functions for Data Analysis

Activity 5.01: Analyzing Sales Using Window Frames and Window Functions

Solution:

The solution to this activity is as follows:

  1. Open pgAdmin, connect to the sqlda database, and open SQL query editor.
  2. Calculate the total sales amount by day for all the days in the year 2021 (that is, before the date January 1, 2022).
  3. The query for this step will be:
    SELECT 
      sales_transaction_date::date, 
      SUM(sales_amount) sales_amount
    FROM 
      sales
    WHERE
      sales_transaction_date::date BETWEEN '20210101' AND '20211231'
    GROUP BY
      sales_transaction_date::date;

The result is:

Figure 5.18: Daily Sales of 2021

  1. Calculate the rolling 30-day average for the daily number of sales deals. The query for this step will be:

Activity5.01.sql

1 WITH 
2  daily_sales as (
3    SELECT 
4      sales_transaction_date::date, 
5      SUM(sales_amount) sales_amount
6    FROM 
7      sales
8...