我对SQL和postgres比较陌生。我将R1和R2与少量列相关联,每个列都有一些测量值,比如R1.m和R2.m。现在我需要为R1中的每一行找到(R1.m和R2.m)f(R1.m,R2.m)
的某个函数f的最小值,以便代码类似于select R1.name, R2.name from R1,R2 where f(R1.m,R2.m) < .......
。我无法填写此查询。我需要在R1中的每一行使用一行R2,这样可以最大限度地减少功能。我知道这很简单,只是不能为新手工作。 (在postgres中)
答案 0 :(得分:0)
不确定我是否正确地解决了你的问题,尝试这样的事情:
with
r1 as (select generate_series(1,10,1) as m)
,r2 as (select generate_series(10,20,1) as m)
,cte as (
select
r1.m as "r1.m",
r2.m as "r2.m",
sin(r1.m * r2.m) f_r1r2,
dense_rank() over (partition by r1.m order by sin(r1.m * r2.m)) as f_r1r2_rank
from
r1,
r2
)
select
*
from
cte
where
f_r1r2_rank = 1
这将:
r1
和r2
(获取r1.m
和r2.m
的所有可能组合)f
(在我的例子中,我使用sin(r1.m*r2.m)
作为示例)r1
和r2
换句话说,这将回答问题:&#34; r2.m
我应该使用f(r1.m,r2.m)
来获得r1.m
给定with
cte as (
select
r1.m as "r1.m",
r2.m as "r2.m",
sin(r1.m * r2.m) f_r1r2,
dense_rank() over (partition by r1.m order by sin(r1.m * r2.m)) as f_r1r2_rank
from
r1,
r2
)
select
*
from
cte
where
f_r1r2_rank = 1
的最小功能?&#34;。
因为您没有提供样本数据,所以我已经创建了自己的样本数据。为了使它工作,你必须使用类似的东西:
sin(r1.m * r2.m)
当然,您必须使用自己的功能替换{{1}}。
答案 1 :(得分:0)
如果我明白了
select distinct on (r1.name)
r1.name, r2.name, f(r1.m, r2.m)
from r1 cross join r2
order by r1.name, f(r1.m, r2.m)
distinct on
将只返回一个r1.name
,第一个是根据order by
子句计算的。