Advertisement
Step8rother

Как сочетать объединения и подзапросы, задача 4

Jun 29th, 2023
2,442
1
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.83 KB | Source Code | 1 0
  1. /*Определите, летом какого года общая выручка в магазине была максимальной. Затем проанализируйте данные за этот год по странам. Выгрузите таблицу с полями:
  2. country — название страны;
  3. total_invoice — число заказов, оформленных в этой стране в тот год, когда общая выручка за лето была максимальной;
  4. total_customer — число клиентов, зарегистрированных в этой стране.
  5. Отсортируйте таблицу по убыванию значений в поле total_invoice, а затем добавьте сортировку по названию страны в лексикографическом порядке.
  6. */
  7.  
  8. --задача выполняется в два этапа:
  9. --1. сначала опредеяем лучшее лето
  10. SELECT EXTRACT(YEAR FROM CAST(invoice_date AS DATE)) AS YEAR,
  11.        SUM(total)
  12. FROM invoice
  13. WHERE EXTRACT(MONTH FROM CAST(invoice_date AS DATE)) IN (6, 7, 8)
  14. GROUP BY EXTRACT(YEAR FROM CAST(invoice_date AS DATE))
  15. ORDER BY SUM(total) DESC;
  16.  
  17. -затем анализируем данные за этот год по странам
  18. SELECT sub_one.country,
  19.        sub_one.total_invoice,
  20.        sub_two.total_customer
  21. FROM
  22.   (SELECT invoice.billing_country AS country,
  23.           COUNT(invoice.total) AS total_invoice
  24.    FROM invoice
  25.    WHERE EXTRACT(YEAR FROM CAST(invoice_date AS DATE)) = 2011
  26.    GROUP BY country) AS sub_one
  27. LEFT JOIN
  28.   (SELECT country,
  29.           COUNT(customer_id) AS total_customer
  30.    FROM client
  31.    GROUP BY country) AS sub_two ON sub_one.country = sub_two.country
  32. ORDER BY total_invoice DESC,
  33.          country;
Advertisement
Comments
  • t7235
    1 year
    # text 0.74 KB | 0 0
    1. можно и короче
    2.  
    3. SELECT i.billing_country AS country,
    4. COUNT(i.invoice_id) AS total_invoice,
    5. tc.total_customer
    6. FROM invoice AS i
    7. LEFT JOIN (SELECT billing_country,
    8. COUNT(DISTINCT customer_id) AS total_customer
    9. FROM invoice
    10. GROUP BY billing_country) AS tc ON i.billing_country = tc.billing_country
    11. WHERE EXTRACT(YEAR FROM CAST(i.invoice_date AS timestamp)) = (
    12. SELECT EXTRACT(YEAR FROM CAST(invoice_date AS timestamp)) AS invoice_year
    13. FROM invoice
    14. WHERE EXTRACT(MONTH FROM CAST(invoice_date AS timestamp)) IN (6, 7, 8)
    15. GROUP BY invoice_year
    16. ORDER BY SUM(total) DESC
    17. LIMIT 1)
    18. GROUP BY country, total_customer
    19. ORDER BY total_invoice DESC, country;
Add Comment
Please, Sign In to add comment
Advertisement