To do a crosstab/pivot in sqlite one can use the case statement as described, eg, here. However, one cannot do calculations on such ‘generated’ columns, ie, divide the content of the ‘Puma’ column by the ‘Fiesta’ column.
My workaround has been to create an auxiliary view containing the ‘Puma’ and ‘Fiesta’ columns and join this view to the main ‘crosstab’ output and divide the columns from the joined auxiliary table.
CREATE VIEW aux_table AS SELECT
shop_id,
sum(CASE WHEN product = 'Fiesta' THEN units END) as Fiesta,
sum(CASE WHEN product = 'Focus' THEN units END) as Focus`
FROM sales
GROUP BY shop_id;
SELECT
shop_id,
sum(CASE WHEN product = 'Fiesta' THEN units END) as Fiesta,
sum(CASE WHEN product = 'Focus' THEN units END) as Focus,
sum(CASE WHEN product = 'Puma' THEN units END) as Puma,
at.Fiesta/at.Focus 'ratio between Fiesta and Focus'
FROM sales
JOIN aux_table at ON
sales.shop_id = at.shop_id
GROUP BY shop_id;
But I wonder whether there is a simpler way to do this.
You can always just do the sums again, like so:
Or, faster, you can wrap it up in a subquery, like this: