Add temporary table with index for speeding up consumption graph query
This commit is contained in:
parent
87366336c5
commit
bd3ca2f413
@ -74,30 +74,40 @@ LEFT JOIN garfield.inventory_items AS b
|
||||
AND b.bought > a.bought
|
||||
GROUP BY a.item_id;
|
||||
|
||||
-- We need to create this table so that we can put an index on it
|
||||
-- Otherwise the join in the consumption graph query becomes much slower
|
||||
-- Perhaps it would be nicer to use a materialized view instead
|
||||
DROP TABLE IF EXISTS last_n_days;
|
||||
CREATE TEMPORARY TABLE last_n_days AS (
|
||||
SELECT
|
||||
generate_series(now() - interval '14 days', now(), interval '1 day')::date AS sale_date
|
||||
);
|
||||
CREATE UNIQUE INDEX last_n_days_sale_date ON last_n_days (sale_date);
|
||||
|
||||
-- Get an array of how often items were sold over the last 14 days
|
||||
CREATE TEMPORARY VIEW inventory_last_n_days_sales AS
|
||||
WITH
|
||||
last_n_days AS (
|
||||
SELECT generate_series(now() - interval '14 days', now(), interval '1 day')::date AS sale_date
|
||||
),
|
||||
last_n_days_sales AS (
|
||||
sales_by_date AS (
|
||||
SELECT
|
||||
item_id,
|
||||
sale_date,
|
||||
count(snack_sales_log_timestamp) AS sale_date_sales
|
||||
inventory_line AS item_id,
|
||||
date_trunc('day', snack_sales_log_timestamp AT TIME ZONE 'UTC+1') AS sale_date,
|
||||
count(*)::int AS sales
|
||||
FROM garfield.snack_sales_log
|
||||
GROUP BY item_id, sale_date
|
||||
),
|
||||
beeg AS (
|
||||
SELECT item_id, sale_date, count(snack_sales_log_timestamp)::int AS sales
|
||||
FROM garfield.inventory_items
|
||||
LEFT JOIN garfield.inventory_map ON item_id = inventory_id
|
||||
-- Is there a better way of writing this?
|
||||
-- TODO: Try to speed this query up
|
||||
CROSS JOIN last_n_days
|
||||
LEFT JOIN garfield.snack_sales_log
|
||||
ON inventory_map.snack_id = snack_sales_log.snack_id
|
||||
AND DATE_TRUNC('day', snack_sales_log_timestamp) = sale_date
|
||||
ON inventory_line = item_id
|
||||
-- snack_sales_log has an index on snack_sales_log_timestamp to speed up this query
|
||||
-- If that index doesn't exist the query takes much longer.
|
||||
AND sale_date = date_trunc('day', snack_sales_log_timestamp AT TIME ZONE 'UTC+1')
|
||||
WHERE available
|
||||
GROUP BY item_id, sale_date
|
||||
ORDER BY item_id, sale_date
|
||||
)
|
||||
SELECT
|
||||
item_id,
|
||||
array_agg(sale_date_sales) AS last_n_days_sales
|
||||
FROM last_n_days_sales
|
||||
SELECT item_id, array_agg(sales) AS last_n_days_sales
|
||||
FROM beeg
|
||||
GROUP BY item_id
|
||||
|
Loading…
x
Reference in New Issue
Block a user