SET height = '500';
SET type = 'pie';

SET group_by = (CASE
WHEN (SELECT count(DISTINCT "group") FROM sqlpage_txn) > 2
THEN 'Group'
WHEN (SELECT count(DISTINCT category) FROM sqlpage_txn) > 2
THEN 'Category'
ELSE 'Product'
END);
SET total = (SELECT sum(price) FROM sqlpage_txn);
SELECT 'chart' AS component
, 'Share of $'||to_char($total::numeric, 'FM999999999.00') AS title
, $height AS height
, $type AS type
, TRUE AS labels
;
SELECT "group" AS series
, sum(price) AS value
FROM sqlpage_txn
WHERE $group_by = 'Group'
GROUP BY "group"
;
SELECT category AS series
, sum(price) AS value
FROM sqlpage_txn
WHERE $group_by = 'Category'
GROUP BY category
;
SELECT product AS series
, sum(price) AS value
FROM sqlpage_txn
WHERE $group_by = 'Product'
GROUP BY product
;
