+-------------+---------+
|Column Name |Type|+-------------+---------+
| product_id | int || name | varchar |+-------------+---------+
product_id is the columnwithuniquevaluesfor this table.
This tablecontains the ID and the name of the product. The name consists ofonly lowercase English letters. No two products have the same name.
Table: Invoice
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
+-------------+------+
|Column Name |Type|+-------------+------+
| invoice_id | int || product_id | int || rest | int || paid | int || canceled | int || refunded | int |+-------------+------+
invoice_id is the columnwithuniquevaluesfor this tableand the id of this invoice.
product_id is the id of the product for this invoice.
rest is the amount leftto pay for this invoice.
paid is the amount paid for this invoice.
canceled is the amount canceled for this invoice.
refunded is the amount refunded for this invoice.
Write a solution that will, for all products, return each product name with the total amount due, paid, canceled, and refunded across all invoices.
Input:
Product table:+------------+-------+| product_id | name |+------------+-------+|0| ham ||1| bacon |+------------+-------+Invoice table:+------------+------------+------+------+----------+----------+| invoice_id | product_id | rest | paid | canceled | refunded |+------------+------------+------+------+----------+----------+|23|0|2|0|5|0||12|0|0|4|0|3||1|1|1|1|0|1||2|1|1|0|1|1||3|1|0|1|1|1||4|1|1|1|1|0|+------------+------------+------+------+----------+----------+Output:
+-------+------+------+----------+----------+| name | rest | paid | canceled | refunded |+-------+------+------+----------+----------+| bacon |3|3|3|3|| ham |2|4|5|3|+-------+------+------+----------+----------+Explanation:
- The amount of money left to pay for bacon is1+1+0+1=3- The amount of money paid for bacon is1+0+1+1=3- The amount of money canceled for bacon is0+1+1+1=3- The amount of money refunded for bacon is1+1+1+0=3- The amount of money left to pay for ham is2+0=2- The amount of money paid for ham is0+4=4- The amount of money canceled for ham is5+0=5- The amount of money refunded for ham is0+3=3
SELECT p.name, SUM(i.rest) AS rest, SUM(i.paid) AS paid, SUM(i.canceled) AS canceled, SUM(i.refunded) AS refunded
FROM Product p
JOIN Invoice i ON p.product_id = i.product_id
GROUPBY p.name
ORDERBY p.name;
1
2
3
4
5
SELECT p.name, SUM(i.rest) AS rest, SUM(i.paid) AS paid, SUM(i.canceled) AS canceled, SUM(i.refunded) AS refunded
FROM Product p
JOIN Invoice i ON p.product_id = i.product_id
GROUPBY p.name
ORDERBY p.name;
1
2
3
4
5
6
7
# Assume Product and Invoice are pandas DataFramesimport pandas as pd
defproducts_worth_over_invoices(Product: pd.DataFrame, Invoice: pd.DataFrame) -> pd.DataFrame:
merged = Product.merge(Invoice, on='product_id')
result = merged.groupby('name')[['rest', 'paid', 'canceled', 'refunded']].sum().reset_index()
result = result.sort_values('name').reset_index(drop=True)
return result