Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Определите, летом какого года общая выручка в магазине была максимальной. Затем проанализируйте данные за этот год по странам. Выгрузите таблицу с полями:
- country — название страны;
- total_invoice — число заказов, оформленных в этой стране в тот год, когда общая выручка за лето была максимальной;
- total_customer — число клиентов, зарегистрированных в этой стране.
- Отсортируйте таблицу по убыванию значений в поле total_invoice, а затем добавьте сортировку по названию страны в лексикографическом порядке.
- */
- --задача выполняется в два этапа:
- --1. сначала опредеяем лучшее лето
- SELECT EXTRACT(YEAR FROM CAST(invoice_date AS DATE)) AS YEAR,
- SUM(total)
- FROM invoice
- WHERE EXTRACT(MONTH FROM CAST(invoice_date AS DATE)) IN (6, 7, 8)
- GROUP BY EXTRACT(YEAR FROM CAST(invoice_date AS DATE))
- ORDER BY SUM(total) DESC;
- -затем анализируем данные за этот год по странам
- SELECT sub_one.country,
- sub_one.total_invoice,
- sub_two.total_customer
- FROM
- (SELECT invoice.billing_country AS country,
- COUNT(invoice.total) AS total_invoice
- FROM invoice
- WHERE EXTRACT(YEAR FROM CAST(invoice_date AS DATE)) = 2011
- GROUP BY country) AS sub_one
- LEFT JOIN
- (SELECT country,
- COUNT(customer_id) AS total_customer
- FROM client
- GROUP BY country) AS sub_two ON sub_one.country = sub_two.country
- ORDER BY total_invoice DESC,
- country;
Advertisement
Comments
-
- можно и короче
- SELECT i.billing_country AS country,
- COUNT(i.invoice_id) AS total_invoice,
- tc.total_customer
- FROM invoice AS i
- LEFT JOIN (SELECT billing_country,
- COUNT(DISTINCT customer_id) AS total_customer
- FROM invoice
- GROUP BY billing_country) AS tc ON i.billing_country = tc.billing_country
- WHERE EXTRACT(YEAR FROM CAST(i.invoice_date AS timestamp)) = (
- SELECT EXTRACT(YEAR FROM CAST(invoice_date AS timestamp)) AS invoice_year
- FROM invoice
- WHERE EXTRACT(MONTH FROM CAST(invoice_date AS timestamp)) IN (6, 7, 8)
- GROUP BY invoice_year
- ORDER BY SUM(total) DESC
- LIMIT 1)
- GROUP BY country, total_customer
- ORDER BY total_invoice DESC, country;
Add Comment
Please, Sign In to add comment
Advertisement