使用视图中的where子句

时间:2014-10-23 01:31:31

标签: sql postgresql stored-procedures view parameter-passing

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
;
  1. 这是我正在处理的问题的简化查询
  2. 但是,我希望能够在视图中添加WHERE子句。这样的事情WHERE promotion.created_at > ?
  3. 问题:

    我应该如何修改视图,以便我可以这样做:

    SELECT * 
    FROM summary 
    WHERE promotion.created_at > [timestamp]
    

    我目前无法执行此操作,因为GROUP BY上有inventory_id因此promotion.created_at未被捕获

1 个答案:

答案 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(...)适应您的实际数据类型。