2016-04-29 54 views
3

我有以下查询:计算列(重量/ MAX(重量)

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) 

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

+0

没有group by子句的任何聚合函数(如max())会将结果集合折成单个记录。 – Shadow

+0

我尝试了一组,但我的计算列收到每行相同的答案。 – ULuFlanders

+0

@ULuFlanders,因为你必须使用子查询作为除数,请检查我的答案。 –

回答

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); 
+0

我更喜欢这个解决方案,但是它不会过滤掉以下Where和And子句过滤掉的权重。对不起,如果我的问题没有反映更清楚。 – ULuFlanders

+0

然后在子查询中必须添加相同的条件,包括任何连接不幸。 – Shadow