无法获得postgres来识别函数中的输入变量

时间:2014-01-12 14:52:29

标签: postgresql stored-procedures

我在这里做错了什么?

我想编写一个函数,返回一个表格,其中包含我们所有产品令人沮丧的产品

两个日期之间的表现 - “惨淡”意味着营销成本超过了利润。我

有三个表:产品,支出和交易。

CREATE TABLE products
(id int not null, name varchar(255), primary key (id));

CREATE TABLE spend
(id int not null, spenddate date, spendamount decimal (9, 2));

CREATE TABLE transactions
(id int not null, transactiondate date, profit decimal (9, 2));

我要做的是在两个表之间进行联合查询,然后将它们相加以获得每行

产物:

WITH a as (
SELECT products.id, products.name, 
sum(transactions.profit) as profit,
sum(0) as spendamount
FROM transactions
WHERE transactiondate BETWEEN startdate AND enddate
GROUP BY products.id, products.name
UNION ALL
SELECT id, sum(0) as profit
sum(amount) as spendamount
FROM spend
WHERE spenddate BETWEEN startdate AND enddate
GROUP BY id)
SELECT products.id, products.name, sum(profit)-sum(spendamount) as loss
FROM a, products
WHERE products.id = a.id
GROUP BY products.id, products.name
HAVING sum(profit)-sum(spendamount) < 0;

但我不希望每次运行代码时都不断更改start和enddate值。

我以为我会这样做:

CREATE FUNCTION report_dismal_products (startdate date, enddate date,
out id int,
out name varchar(255),
out loss decimal(9, 2)

)
RETURNS SETOF RECORD 
 as $$

SELECT products.id, products.name, sum(profit)-sum(spendamount) as loss
FROM 
(
SELECT id, 
sum(transactions.profit) as profit,
sum(0) as spendamount
FROM transactions
WHERE transactiondate BETWEEN startdate AND enddate
GROUP BY id
UNION ALL
SELECT id, sum(0) as profit
sum(amount) as spendamount
FROM spend
WHERE spenddate BETWEEN startdate AND enddate
GROUP BY id) a, products
WHERE products.id = a.id
GROUP BY products.id, products.name
HAVING sum(profit)-sum(spendamount) < 0;

$$ Language sql;

但它返回

ERROR:  column "startdate" does not exist
LINE 17:     WHERE transactiondate BETWEEN startdate AND enddate

0 个答案:

没有答案