Advertisement
Step8rother

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

Jun 29th, 2023 (edited)
2,714
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.96 KB | Source Code | 0 0
  1. /*Составьте сводную таблицу. Посчитайте заказы, оформленные за каждый месяц в течение нескольких лет: с 2011 по 2013 год. Итоговая таблица должна включать четыре поля: invoice_month, year_2011, year_2012, year_2013. Поле invoice_month должно хранить месяц в виде числа от 1 до 12.
  2. Если в какой-либо месяц заказы не оформляли, номер такого месяца всё равно должен попасть в таблицу.
  3. В этом задании не будет подсказок. Используйте любые методы, которые посчитаете нужными.
  4. */
  5.  
  6. SELECT i_month.invoice_month,
  7.        inv_2011.year_2011,
  8.        inv_2012.year_2012,
  9.        inv_2013.year_2013
  10. FROM
  11.   (SELECT EXTRACT(MONTH FROM CAST(invoice_date AS DATE)) AS invoice_month
  12.    FROM invoice
  13.    GROUP BY invoice_month
  14.    ORDER BY invoice_month) AS i_month
  15.    
  16.    
  17. LEFT JOIN
  18.   (SELECT EXTRACT(MONTH FROM CAST(invoice_date AS DATE)) AS invoice_month,
  19.           COUNT(invoice_id) AS year_2011
  20.    FROM invoice
  21.    WHERE EXTRACT(YEAR FROM CAST(invoice_date AS DATE)) = 2011
  22.    GROUP BY invoice_month) AS inv_2011 ON i_month.invoice_month = inv_2011.invoice_month
  23.    
  24.    
  25. LEFT JOIN
  26.   (SELECT EXTRACT(MONTH FROM CAST(invoice_date AS DATE)) AS invoice_month,
  27.           COUNT(invoice_id) AS year_2012
  28.    FROM invoice
  29.    WHERE EXTRACT(YEAR FROM CAST(invoice_date AS DATE)) = 2012
  30.    GROUP BY invoice_month) AS inv_2012 ON i_month.invoice_month = inv_2012.invoice_month
  31.    
  32.    
  33. LEFT JOIN
  34.   (SELECT EXTRACT(MONTH FROM CAST(invoice_date AS DATE)) AS invoice_month,
  35.           COUNT(invoice_id) AS year_2013
  36.    FROM invoice
  37.    WHERE EXTRACT(YEAR FROM CAST(invoice_date AS DATE)) = 2013
  38.    GROUP BY invoice_month) AS inv_2013 ON i_month.invoice_month = inv_2013.invoice_month
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement