我想计算过去7天,30天,90天和180天每天平均花费的金额。我知道如何使用PL / pgSQL来完成它,但如果可能的话,我更愿意在一个查询中完成它。像这样:
SELECT SUM(amount)/days
FROM transactions
WHERE created_at > CURRENT_DATE - ((days || ' day')::INTERVAL)
AND days = ANY(ARRAY[7,30,90,180]);
ERROR: column "days" does not exist
答案 0 :(得分:1)
您可以使用unnest
将数组转换为表格,并使用相关子查询来计算平均值:
SELECT
days,
(SELECT SUM(amount)/days
FROM transactions
WHERE created_at > CURRENT_DATE - ((days || ' day')::INTERVAL)
) AS average
FROM unnest(ARRAY[7,30,90,180]) t(days)