scratch.sql 1.2 KB

12345678910111213141516171819202122
  1. --Monthly report, breakdown by group
  2. SELECT year, month, "group", total_price FROM (
  3. SELECT
  4. groups.name AS "group",
  5. date_part('year',ts) AS year,
  6. date_part('month', ts) AS month,
  7. units.name AS unit,
  8. TRUNC(sum(price),2) AS total_price
  9. FROM transactions AS t
  10. JOIN products ON (product_id = products.id)
  11. JOIN categories ON (category_id = categories.id)
  12. JOIN groups ON (group_id = groups.id)
  13. JOIN units ON (unit_id = units.id)
  14. WHERE date_part('year',ts) IN (2021, 2022)
  15. GROUP BY
  16. date_part('year',ts),
  17. ROLLUP(groups.name, date_part('month', ts), units.name)
  18. ORDER BY year, month, "group", unit
  19. ) AS subq WHERE unit IS NULL AND month IS NOT NULL AND "group" IS NOT NULL;
  20. --Group monthly trend
  21. SELECT * FROM (SELECT groups.name AS "group", date_part('year',ts) AS year, date_part('month', ts) AS month, TRUNC(sum(price),2) AS total_price FROM transactions AS t JOIN products ON (product_id = products.id) JOIN categories ON (category_id = categories.id) JOIN groups ON (group_id = groups.id) JOIN units ON (unit_id = units.id) WHERE date_part('year',ts) IN (2021, 2022) GROUP BY ROLLUP(groups.name, date_part('year', ts), date_part('month', ts)) ORDER BY "group",year, month) AS subq WHERE month IS NOT NULL;