I'm relatively new to SQL and postgres. I've relation R1 and R2 with few columns , one each being some measurement,say R1.m and R2.m . Now i need to find for every row in R1 , the minimum of some function f of (R1.m and R2.m) , f(R1.m,R2.m)
so that the code is something like select R1.name, R2.name from R1,R2 where f(R1.m,R2.m) < .......
. I'm not able to fill up this query . I need a row of R2 for every row in R1 which minimizes the function. I know this is simple , just cant work it out for a newbie . (In postgres)
问问题
158 次
2 回答
0
Not sure I undrestand your question correctly, try something like this:
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
This will:
- Create cross product or
r1
andr2
(get all possible combinations ofr1.m
andr2.m
) - Calculate function
f
(in my case I usedsin(r1.m*r2.m)
as an example) - Calculate rank for every set of combination of
r1
andr2
- Select only those where rank = 1 (minimum)
In other words this will answer question: "What r2.m
should I use to get minimum of function f(r1.m,r2.m)
given r1.m
?".
Because you have not provided sample data, I've generated my own. To make it work, you have to use something like:
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
and of course, you have to replace sin(r1.m * r2.m)
with your own function.
于 2013-09-16T10:35:25.067 回答
0
If I understand it
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
will return one only r1.name
, the first one computed from the order by
clause.
于 2013-09-16T12:27:28.123 回答