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

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