SQL SERIES #4: LEAD() Window Function

Problem Statement

Given a table sales_data that logs daily sales figures for multiple stores, the goal is to calculate the percentage change in sales from one day to the next for each store.


Input

The table sales_data has the following structure:

  • store_id (integer): Identifier for the store
  • sale_date (date): The date of the sale
  • sales_amount (decimal): The amount of sales for that day


Code


Code Explanation:

The LEAD() function in SQL is used to access data from the subsequent row within the same result set. It retrieves values from a following row based on a specified offset, allowing for comparisons between current and future rows. In the query above, LEAD(sales_amount, 1) fetches the sales amount for the next day to compute the percentage change in sales from one day to the next.

The WITH sales_comparison AS clause creates a Common Table Expression (CTE) to prepare the data. The LEAD(sales_amount, 1) function retrieves the sales amount for the next day within the same store, using PARTITION BY store_id and ORDER BY sale_date for proper sequencing. The final SELECT statement includes the original sales data and computes the percentage change from the current day to the next day using a CASE statement


Output


A nice and sweet tutorial. Definitely post more challenges. I think people don't consider LinkedIn a source of "knowledge", but SQL tutorials like this show otherwise.

要查看或添加评论,请登录

Nischal Subedi的更多文章

  • SQL Series #3: ROW_NUMBER() Window Function

    SQL Series #3: ROW_NUMBER() Window Function

    Problem Statement: Imagine you work for a retail company, and you want to analyze the performance of your salespeople…

  • AWS AI Service: Amazon Rekognition

    AWS AI Service: Amazon Rekognition

    Amazon Rekognition is an AI service that enables users to effortlessly incorporate image and video analysis into their…

  • SQL Series #2: Calculating Loyalty Points with INTERVAL

    SQL Series #2: Calculating Loyalty Points with INTERVAL

    Problem Statement In the first week after joining (including the join date), customers earn 2x points on all items, not…

    1 条评论
  • SQL Series #1: Dense_Rank() Window Function

    SQL Series #1: Dense_Rank() Window Function

    ?? Problem Statement Write a query that outputs the name of the credit card and how many cards were issued in its…

社区洞察

其他会员也浏览了