HardNo. 1384LeetCode Premium
Total Sales Amount by Year — LeetCode 1384 Python Solution
- Topics
- Database
- Reading time
- 8 min
- Source
- leetcode.com
Table schema
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
+---------------+---------+
| 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
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
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0175 | Combine Two Tables | Easy |
| 0176 | Second Highest Salary | Medium |
| 0177 | Nth Highest Salary | Medium |
| 0178 | Rank Scores | Medium |
| 0180 | Consecutive Numbers | Medium |
| 0181 | Employees Earning More Than Their Managers | Easy |
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.