14. Calculate Cumulative Sales
Beginner Mode
Objective
Given a table sales_data containing product sales with the following columns:
| Column | Type | Description |
|---|---|---|
| daily_sales | INTEGER | The number of units sold on that date |
| date | DATE | The date of the sale |
| product_name | VARCHAR | The name of the product sold |
Write a SQL query to retrieve each record along with a new column cumulative_sales that represents the running total of sales for each product up to and including the current date. The results should be ordered first by product_name and then by date.
Additional information
Constraints:
- The
sales_datatable can contain multiple products with sales data spanning multiple dates. - Dates for each product are unique and sorted chronologically.
- The
Output Format:
- The output should include the following columns:
cumulative_sales,daily_sales,date,product_name.
- The output should include the following columns:
Examples
Example 1:
Output:
Input:
| sales_data | ||
|---|---|---|
| daily_sales | date | product_name |
| 1000 | 2023-01-01 | Laptop |
| 1500 | 2023-01-02 | Laptop |
| 800 | 2023-01-03 | Laptop |
| 500 | 2023-01-01 | Phone |
| 600 | 2023-01-02 | Phone |
| 750 | 2023-01-03 | Phone |
| cumulative_sales | daily_sales | date | product_name |
|---|---|---|---|
| 1000 | 1000 | 2023-01-01 | Laptop |
| 2500 | 1500 | 2023-01-02 | Laptop |
| 3300 | 800 | 2023-01-03 | Laptop |
| 500 | 500 | 2023-01-01 | Phone |
| 1100 | 600 | 2023-01-02 | Phone |
| 1850 | 750 | 2023-01-03 | Phone |
Code Environment
Sign in or try as guest to run your code.
Essential
SQL 0/33
Spark 0/20
Snowflake 0/22
Python 0/24
Need more practice in this area? Explore more questions →
Uber
Revolut
Accenture
Adobe
Google
LinkedIn
Samsung
Datadog
Wix
Dropbox
Meta
OpenAI
Hulu
X
DoorDash
Anthropic
Amazon
ActivisionBlizzard
Vercel
Crypto.Com
Zscaler
DeutscheBank
Apple
GoDaddy
GitLab
BMW
PayPal
Snowflake
AMD
Twilio
Atlassian
JPMorgan
NVIDIA
IBM
Databricks
Coinbase
Cisco
Robinhood
Twitter
Microsoft
Palantir
Netflix
VMware
Cloudflare
Stripe
Lyft
Salesforce
GitHub
Bloomberg
Airbnb
Walmart
SAP
HashiCorp
Instacart
Mastercard
Intel
Visa
Tesla