Daily LeetCode #7
Some notes on problems from SQL 50.


SELECT P.product_id,
IFNULL(round(sum(P.price * U.units) / sum(U.units), 2), 0) AS average_price
FROM Prices AS P LEFT OUTER JOIN UnitsSold AS U ON P.product_id = U.product_id AND U.purchase_date BETWEEN P.start_date AND P.end_date
GROUP BY P.product_idNotes:
- the result should include all the
product_id, so we need to useLEFT OUTER JOIN, otherwise we will lose those ids withNULLinaverage_price - combine with
IFNULL,NULLcan be converted into0 - function
a BETWEEN b AND c: check if date variableain between datecand dated

SELECT SUBSTR(T.trans_date, 1, 7) AS month,
T.country, count(*) AS trans_count,
sum(IF(T.state = "approved", 1, 0)) AS approved_count,
sum(T.amount) AS trans_total_amount,
sum(IF(T.state = "approved", T.amount, 0)) AS approved_total_amount
FROM Transactions AS T
GROUP BY month, country- use
SUBSTR(a, positive: start from beginning; negative: start from the end, length)to extract year-month fromdateattribute - can use
EXTRACT(MONTH FROM date)to extract onlymonth - can use
EXTRACT(YEAR FROM date)to extract onlyyear