在 SQL 中,一种方法是使用连接和聚合:
select t.id,
max(t.A)*max(case when p.col = 'A' then p.coefficient end),
max(t.B)*max(case when p.col = 'B' then p.coefficient end),
. . .
from data t cross join
parameters p
group by t.id
您也可以在select
语句中使用内联查询来执行此操作:
select t.A*(select max(coefficient) from parameters where col = 'A'),
. . .
from data t
假设您没有太多数据(您有数千行,而不是数百万行),任何一种方法都应该合理地执行。
顺便说一句,如果参数存储在一行中,那么简单的连接和乘法就足够了。
还有另一种方法,类似于第一种方法,但可能更清楚:
select t.id,
t.A*p.Acoefficient,
t.B*p.Bcoefficient,
. . .
from data t cross join
(select max(case when p.col = 'A' then coefficient end) as Acoefficient,
max(case when p.col = 'B' then coefficient end) as Bcoefficient,
...
parameters p
) p
我正在添加这个,因为这可能是我真正编写解决方案的方式。