Code Generator | SQL

Create Customer Revenue Table Function

This SQL function generates a CustomerRevenue table summarizing total revenue per customer with associated dates by aggregating sales data, ensuring efficient analysis of revenue trends.


Empty image or helper icon

Prompt

builds a table contaning customer namne, revenue per customer, revenue date

Answer

SQL Function to Create Customer Revenue Table

Overview

This SQL function creates a table that contains customer names, revenue per customer, and the associated revenue dates. The function assumes you have an existing sales data table from which the required information will be extracted.

Function Definition

SQL Code

CREATE OR REPLACE FUNCTION CreateCustomerRevenueTable()
RETURNS VOID AS $$
BEGIN
    -- Drop the table if it already exists
    DROP TABLE IF EXISTS CustomerRevenue;

    -- Create a new table for customer revenue
    CREATE TABLE CustomerRevenue AS
    SELECT 
        c.CustomerName,         -- Select the customer name
        SUM(s.Revenue) AS TotalRevenue, -- Calculate total revenue per customer
        s.RevenueDate           -- Include the date of the revenue
    FROM 
        Customers c             -- Main customer table
    JOIN 
        Sales s ON c.CustomerID = s.CustomerID  -- Join with sales table based on CustomerID
    GROUP BY 
        c.CustomerName, 
        s.RevenueDate;          -- Group by customer name and revenue date

    -- Log the success of the table creation
    RAISE NOTICE 'CustomerRevenue table created successfully.';
END;
$$ LANGUAGE plpgsql;

Key Components

  • Imports: No specific imports are required in standard SQL, but this function utilizes PostgreSQL's PL/pgSQL.
  • Function Purpose: This function creates a table that summarizes the total revenue per customer per date, allowing for easy analysis of revenue trends.
  • Parameters: The function does not require input parameters.
  • Return Type: Returns VOID, indicating it creates a table rather than returning values.
  • Exceptions: Will raise an error if the function encounters issues during execution.

Input Validation and Comments

  • The function drops the existing CustomerRevenue table (if it exists) to avoid conflicts.
  • It uses JOIN to combine the Customers and Sales tables based on the customer ID, ensuring accurate revenue mapping.
  • The SUM function is employed to aggregate revenue data, and GROUP BY is utilized to structure the output correctly.
  • Comments within the code clarify each function's purpose and logic.

Usage Example

To execute this function and create the CustomerRevenue table, simply run:

SELECT CreateCustomerRevenueTable();

This command will create the CustomerRevenue table in the database, ready for querying.

Conclusion

This SQL function exemplifies best practices in creating a summarization table by:

  • Ensuring scalability through the SUM and GROUP BY clauses.
  • Maintaining code clarity with inline comments and structured logic.
  • Handling potential conflicts with existing tables proactively.

For those interested in further enhancing their SQL skills, consider exploring courses available on the Enterprise DNA platform.

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 function generates a CustomerRevenue table summarizing total revenue per customer with associated dates by aggregating sales data, ensuring efficient analysis of revenue trends.