计算列(权重/最大权重)

3

我有以下查询:

select ema.es_symbol as symbol, ema.score as score, ema.weight as weight, rsi.relative_strength_index as relative_strength_index
from ema_score ema, relative_strength_index rsi inner join
    (select rsi_symbol, max(rsi_date) as maxDate from relative_strength_index group by rsi_symbol) rsiDate
    on rsi.rsi_symbol = rsiDate.rsi_symbol
    and rsi.rsi_date = rsiDate.maxDate
where ema.es_symbol = rsi.rsi_symbol
and ema.score not in (0,1,10,11)
and rsi.relative_strength_index not in (0,100);

我正在尝试添加一个计算列,就像下面这个作为最后一列:

ema.weight/max(ema.weight)

我想要的结果是每个符号的重量除以重量列中的最大重量。当我按照我的方式尝试时,我只收到了一行结果。我在这里做错了什么?

任何聚合函数,例如max(),如果没有group by子句,则会将结果集合并为单个记录。 - Shadow
我尝试了分组,但我的计算列对于每一行都得到了相同的答案。 - ULuFlanders
@ULuFlanders,这是因为你必须使用子查询作为除数,请查看我的答案。 - Stanislovas Kalašnikovas
2个回答

0

你需要使用带有MAX作为除数的子查询,类似于:

select ema.weight*1.0/(select max(weight) from #t ema2)
from #t ema

1
我已将此调整为查询格式,现在可以正常运行。感谢您的回答。 - ULuFlanders

0
任何聚合函数,例如max(),如果没有group by子句,则会将结果集合并为单个记录。您需要在子查询中选择最大值,并使用交叉连接将其与所有记录关联起来。此外,请不要混合使用隐式和显式连接,如果将外部连接添加到查询中,可能会遇到非常令人讨厌的意外情况!
select ema.es_symbol as symbol, ema.score as score, ema.weight as weight, ema.weight/maxweight as percentage, rsi.relative_strength_index as relative_strength_index
from ema_score ema
     join (select max(weight) as maxweight from ema_score) t
     inner join relative_strength_index rsi on ema.es_symbol = rsi.rsi_symbol
     inner join
    (select rsi_symbol, max(rsi_date) as maxDate from relative_strength_index group by rsi_symbol) rsiDate
    on rsi.rsi_symbol = rsiDate.rsi_symbol
    and rsi.rsi_date = rsiDate.maxDate
where ema.score not in (0,1,10,11)
and rsi.relative_strength_index not in (0,100);

我更喜欢这个解决方案,但它不能过滤掉在下面的Where和And子句中被过滤掉的权重。如果我的问题没有表达清楚,我很抱歉。 - ULuFlanders
然后在子查询中,您必须添加相同的where条件,包括任何联接(遗憾地)。 - Shadow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接