CREATE VIEW summary AS
SELECT sales.inventory_id,
sum(sales.value) AS value,
count(sales.*) AS sales_n,
FROM promotion
JOIN sales USING (promotion_id)
GROUP BY sales.inventory_id
;
WHERE
子句。这样的事情WHERE promotion.created_at > ?
问题:
我应该如何修改视图,以便我可以这样做:
SELECT *
FROM summary
WHERE promotion.created_at > [timestamp]
我目前无法执行此操作,因为GROUP BY
上有inventory_id
因此promotion.created_at
未被捕获
答案 0 :(得分:0)
使用 SQL函数将时间戳作为参数:
CREATE FUNCTION summary(_created_at timestamp)
RETURNS TABLE (inventory_id int, value bigint, sales_n int)
AS
$func$
SELECT s.inventory_id
, sum(s.value) -- AS value -- alias not visible outside function
, count(*) -- AS sales_n
FROM promotion p
JOIN sales s USING (promotion_id)
WHERE p.created_at > $1
GROUP BY s.inventory_id
$func$ LANGUAGE sql STABLE;
呼叫:
SELECT * FROM summary('2014-06-01 10:00');
我用表别名缩短了语法。
count(*)
与此处的count(s.*)
相同
使RETURNS TABLE(...)
适应您的实际数据类型。