Total Sales Amount by Year — LeetCode 1384 Python Solution
HardLeetCode PremiumDatabase
- Problem
- #1384
- Reading time
- 8 min
- Source
- leetcode.com
Table schema
SQL
Table: Product +---------------+---------+ | Column Name | Type | +---------------+---------+ | product_id | int | | product_name | varchar | +---------------+---------+ product_id is the primary key (column with unique values) for this table. product_name is the name of the product.Example
SQL
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| product_id | int |
| product_name | varchar |
+---------------+---------+
product_id is the primary key (column with unique values) for this table.
product_name is the name of the product.Python solution
Python
import duckdb
import pandas as pd
def solution(product: pd.DataFrame, sales: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Product", product)
con.register("Sales", sales)
return con.execute("""SELECT
s.product_id,
p.product_name,
y.YEAR report_year,
s.average_daily_sales * (
IF(
YEAR(s.period_end) > y.YEAR,
y.days_of_year,
DAYOFYEAR(s.period_end)
) - IF(
YEAR(s.period_start) < y.YEAR,
1,
DAYOFYEAR(s.period_start)
) + 1
) total_amount
FROM
Sales s
INNER JOIN (
SELECT
'2018' YEAR,
365 days_of_year
UNION
ALL
SELECT
'2019' YEAR,
365 days_of_year
UNION
ALL
SELECT
'2020' YEAR,
366 days_of_year
) y ON YEAR(s.period_start) <= y.YEAR
AND YEAR(s.period_end) >= y.YEAR
INNER JOIN Product p ON p.product_id = s.product_id
ORDER BY
s.product_id,
y.YEAR""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1384. Total Sales Amount by Year?
- LeetCode 1384. Total Sales Amount by Year is rated Hard on LeetCode.
- What topics does LeetCode 1384. Total Sales Amount by Year cover?
- LeetCode 1384. Total Sales Amount by Year is tagged Database on LeetCode.
- Is LeetCode 1384. Total Sales Amount by Year a premium problem?
- Yes. LeetCode 1384. Total Sales Amount by Year is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.