DROP TABLE IF EXISTS sqlpage_tags;
CREATE TABLE IF NOT EXISTS sqlpage_tags AS
SELECT count(DISTINCT txn.id) AS "Uses", tg.name AS "Name"
FROM tags tg
JOIN tags_map tm ON tg.id = tm.tag_id
JOIN transactions txn ON txn.id = tm.transaction_id
JOIN products p ON p.id = txn.product_id
JOIN categories c ON p.category_id = c.id
JOIN groups g ON c.group_id = g.id
WHERE
  (p.name IN (SELECT v#>>'{}' FROM json_array_elements($products::json) j(v)) OR $products IS NULL)
AND
  (c.name IN (SELECT v#>>'{}' FROM json_array_elements($categories::json) j(v)) OR $categories IS NULL)
AND
  (g.name IN (SELECT v#>>'{}' FROM json_array_elements($groups::json) j(v)) OR $groups IS NULL)
AND
  (tg.name IN (SELECT v#>>'{}' FROM json_array_elements($tags::json) j(v)) OR $tags IS NULL)
AND
  ((ts AT TIME ZONE 'UTC') AT TIME ZONE 'Pacific/Auckland')::date
  BETWEEN $start::date AND $end::date
GROUP BY tg.name
ORDER BY 1 DESC, 2
;