DROP TABLE IF EXISTS sqlpage_products;
CREATE TABLE IF NOT EXISTS sqlpage_products AS
--(
--   "Products" int,
--   "Categories" int,
--   "Groups" int,
--   product text,
--   category text,
--   "group" text
-- );
--INSERT INTO sqlpage_products
SELECT
  count(DISTINCT p.id) AS "Products",
  count(DISTINCT c.id) AS "Categories",
  count(DISTINCT g.id) AS "Groups",
  p.name AS "product",
  c.name AS "category",
  g.name AS "group"
FROM products p
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)
GROUP BY ROLLUP ("group", category, product)
;
