43 lines
1.6 KiB
SQL
43 lines
1.6 KiB
SQL
-- Determine for each country the province in which the total number of purchases of product 0 is the highest; list the name of the country, the name of the province, and the number of purchases, both absolute and as a proportion of the total number of purchases in that country.
|
|
|
|
-- Expected Heading: RELATION {country CHARACTER, province CHARACTER, abs INTEGER, prop FLOAT}
|
|
-- How do you treat the default case as showed in the instructions?
|
|
-- How do you treat the case where several provinces of a same country have the same total number of purchases of product 0? You should show all such provinces.
|
|
|
|
|
|
SELECT name AS country, province, abs, prop
|
|
FROM (
|
|
SELECT name AS province, country, max(cnt) as abs, max(cnt)*1.0/sum(cnt) AS prop
|
|
FROM(
|
|
SELECT province, sum(qty) as cnt
|
|
FROM Purchases
|
|
WHERE product = 0
|
|
GROUP BY province
|
|
)
|
|
JOIN Province ON province = Province.ROWID
|
|
GROUP BY country
|
|
)
|
|
JOIN Country ON country = code
|
|
;
|
|
|
|
-- V2
|
|
SELECT country.name, TMP.province, cnt AS abs, cnt*1.0/scnt AS prop
|
|
FROM
|
|
(
|
|
SELECT province.country AS code, province.name AS province, COUNT(Purchases.qty) AS cnt
|
|
FROM province
|
|
LEFT JOIN Purchases ON Purchases.product = 0 AND Purchases.province = province.ROWID
|
|
GROUP BY province.name
|
|
) AS TMP
|
|
JOIN (
|
|
SELECT code, province, MAX(cnt) AS mcnt, SUM(cnt) AS scnt FROM (
|
|
SELECT province.country AS code, province.name AS province, COUNT(Purchases.qty) AS cnt
|
|
FROM province
|
|
LEFT JOIN Purchases ON Purchases.product = 0 AND Purchases.province = province.ROWID
|
|
GROUP BY province.name
|
|
)
|
|
GROUP BY code
|
|
) AS F ON TMP.code = F.code AND TMP.cnt = F.mcnt
|
|
JOIN country ON country.code = TMP.code
|
|
;
|