Sales by Day of the Week — LeetCode 1479 Python Solution

HardLeetCode PremiumDatabase
Problem
#1479
Reading time
4 min

Table schema

SQL
Table: Orders +---------------+---------+ | Column Name | Type | +---------------+---------+ | order_id | int | | customer_id | int | | order_date | date | | item_id | varchar | | quantity | int | +---------------+---------+ (ordered_id, item_id) is the primary key (combination of columns with unique values) for this table. This table contains information on the orders placed.

Example

SQL
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| customer_id   | int     |
| order_date    | date    | 
| item_id       | varchar |
| quantity      | int     |
+---------------+---------+
(ordered_id, item_id) is the primary key (combination of columns with unique values) for this table.
This table contains information on the orders placed.
order_date is the date item_id was ordered by the customer with id customer_id.

Python solution

Python
import duckdb
import pandas as pd

def solution(orders: pd.DataFrame, items: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Orders", orders)
    con.register("Items", items)
    return con.execute("""SELECT
    item_category AS category,
    SUM(IF(DAYOFWEEK(order_date) = '2', quantity, 0)) AS Monday,
    SUM(IF(DAYOFWEEK(order_date) = '3', quantity, 0)) AS Tuesday,
    SUM(IF(DAYOFWEEK(order_date) = '4', quantity, 0)) AS Wednesday,
    SUM(IF(DAYOFWEEK(order_date) = '5', quantity, 0)) AS Thursday,
    SUM(IF(DAYOFWEEK(order_date) = '6', quantity, 0)) AS Friday,
    SUM(IF(DAYOFWEEK(order_date) = '7', quantity, 0)) AS Saturday,
    SUM(IF(DAYOFWEEK(order_date) = '1', quantity, 0)) AS Sunday
FROM
    Orders AS o
    RIGHT JOIN Items AS i ON o.item_id = i.item_id
GROUP BY category
ORDER BY category;""").df()

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1479. Sales by Day of the Week?
LeetCode 1479. Sales by Day of the Week is rated Hard on LeetCode.
What topics does LeetCode 1479. Sales by Day of the Week cover?
LeetCode 1479. Sales by Day of the Week is tagged Database on LeetCode.
Is LeetCode 1479. Sales by Day of the Week a premium problem?
Yes. LeetCode 1479. Sales by Day of the Week is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview