Code Explainer | SQL

SQL Code for Calculating Yearly Cumulative Sales in 2013

This SQL code calculates cumulative sales for each month of year 2013 using Common Table Expressions and Window Functions. It showcases the usage of JOIN, WHERE, GROUP BY clauses with a focus on order dates and sales data.


Empty image or helper icon

Prompt

WITH MonthlySales AS (
    SELECT
        DATE_TRUNC('month', soh.orderdate) AS OrderMonth,
        SUM(sod.orderqty * sod.unitprice) AS TotalSales
    FROM
        sales.salesorderdetail sod
        JOIN sales.salesorderheader soh ON sod.salesorderid = soh.salesorderid
    WHERE
        EXTRACT(YEAR FROM soh.orderdate) = 2013
    GROUP BY
        OrderMonth
),
CumulativeSales AS (
    SELECT
        OrderMonth,
        TotalSales,
        SUM(TotalSales) OVER (ORDER BY OrderMonth) AS CumulativeTotal
    FROM
        MonthlySales
)
SELECT
    OrderMonth,
    CumulativeTotal
FROM
    CumulativeSales
ORDER BY
    OrderMonth

Answer

This provided code is written in SQL, a language for managing and manipulating relational databases. The main function of the code is to calculate cumulative sales for each month of the year 2013.

Code Breakdown:

The code can be divided into three segments:

  1. MonthlySales Subquery: This is a Common Table Expression (CTE) that is generating total sales for each month in 2013. The DATE_TRUNC('month', soh.orderdate) part truncates the order date to the nearest month. It then sums up the sales quantities multiplied by the unit price and groups the results by the OrderMonth.

  2. CumulativeSales Subquery: Another CTE, which calculates the cumulative total of the sales. The SUM(TotalSales) OVER (ORDER BY OrderMonth) AS CumulativeTotal line sums up the total sales from the start of the year to the current row's month, making each row's total dependent on the previous ones.

  3. Main Select Query: This is the final query that retrieves the results from the CumulativeSales CTE, ordering them by the month.

Key Concepts:

  • JOIN Clause: The JOIN clause combines rows from two or more tables based on a related column.

  • WHERE Clause: The WHERE clause filters records that satisfy a specified condition.

  • GROUP BY Clause: The GROUP BY statement groups rows that have the same values in specified columns into aggregated data.

  • Common Table Expression (CTE): The CTE provides a way to define temporary views for a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.

  • Window Function: The SUM() OVER() clause is a window function that operates on a set of rows and returns a single value for each row.

Example:

If we replace the table names and fields with generic ones, it could look like this:

WITH MonthlySales AS (
    SELECT
        DATE_TRUNC('month', t1.date_field) AS OrderMonth,
        SUM(t2.quantity * t2.price) AS TotalSales
    FROM
        table2 t2
        JOIN table1 t1 ON t2.id = t1.id
    WHERE
        EXTRACT(YEAR FROM t1.date_field) = 2013
    GROUP BY
        OrderMonth
),
CumulativeSales AS (
    SELECT
        OrderMonth,
        TotalSales,
        SUM(TotalSales) OVER (ORDER BY OrderMonth) AS CumulativeTotal
    FROM
        MonthlySales
)
SELECT
    OrderMonth,
    CumulativeTotal
FROM
    CumulativeSales
ORDER BY
    OrderMonth

This example showcases the same concept but with generic table and field names. It calculates monthly cumulative sales for the year 2013.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This SQL code calculates cumulative sales for each month of year 2013 using Common Table Expressions and Window Functions. It showcases the usage of JOIN, WHERE, GROUP BY clauses with a focus on order dates and sales data.