This problem asks to calculate the percentage of immediate food deliveries from a Delivery
table. An immediate delivery is defined as one where the order_date
and customer_pref_delivery_date
are the same.
The solution uses a single SQL query to achieve this. Let's break down the query:
SELECT
ROUND(SUM(order_date = customer_pref_delivery_date) / COUNT(*) * 100, 2) AS immediate_percentage
FROM Delivery;
SUM(order_date = customer_pref_delivery_date)
: This is the core of the calculation. The expression order_date = customer_pref_delivery_date
evaluates to 1 (true) if the order date matches the preferred delivery date, and 0 (false) otherwise. SUM
then adds up all the 1s, effectively counting the number of immediate deliveries.
COUNT(*)
: This counts the total number of rows (orders) in the Delivery
table.
/ COUNT(*) * 100
: This divides the count of immediate deliveries by the total number of deliveries and multiplies by 100 to get the percentage.
ROUND(..., 2)
: This rounds the resulting percentage to two decimal places, as required by the problem statement.
AS immediate_percentage
: This assigns the alias "immediate_percentage" to the calculated column in the result set.
The time complexity of this SQL query is dominated by the operations performed on the entire Delivery
table. Specifically, COUNT(*)
and SUM(...)
require a scan of the entire table. Therefore, the time complexity is O(N), where N is the number of rows in the Delivery
table.
The space complexity is O(1) because the query only uses a fixed amount of space to store intermediate results and the final output, regardless of the size of the input table. The space used does not scale with the size of the Delivery
table.
While the provided solution is concise and efficient, one could potentially use a subquery to first count the immediate deliveries and then another subquery to count all deliveries before doing the division and rounding. This approach would be less efficient as it involves multiple passes over the data.
No other programming languages are needed since the problem is directly solvable using SQL.