我无法分解简单的 SQL 查询。我使用 PostgreSQL,但我的问题也与其他 RDBMS 有关。
考虑以下示例。我们有表格订单,我们想找到总金额超过某个限制的第一个订单:
drop table if exists orders cascade;
/**
Table with clients' orders
*/
create table orders(
date timestamp,
amount integer
/**
Other columns omitted
*/
);
/**
Populate with test data
*/
insert into orders(date,amount)
values
('2011-01-01',50),
('2011-01-02',49),
('2011-01-03',2),
('2011-01-04',1000);
/**
Selects first order that caused exceeding of limit
*/
create view first_limit_exceed
as
select min(date) from
(
select o1.date
from orders o1,
orders o2
where o2.date<=o1.date
group by o1.date
having sum(o2.amount) > 100
) limit_exceed;
/**
returns "2011-01-03 00:00:00"
*/
select * from first_limit_exceed;
现在让我们把问题变得更难一点。考虑我们只想找到满足某个谓词的行的总量。我们有很多这样的谓词,创建单独版本的视图 first_limit_exceed 将是可怕的代码重复。所以我们需要一些方法来创建参数化视图并将过滤的行集或谓词本身传递给它。在 Postgres 中,我们可以使用查询语言函数作为参数化视图。但是 Postgres 不允许函数作为参数,既不是行集也不是另一个函数。我仍然可以在客户端或 plpgsql 函数中使用字符串插值,但它容易出错并且难以测试和调试。有什么建议吗?