我有以下表格:
tweets stocks
------------------------------------- -----------------------------
id stock_id nyse_date class quality stock_id _date return
------------------------------------- -----------------------------
1 1 2011-03-12 3 1 2011-03-12 0.44
2 1 2011-03-12 1 1 2011-03-15 0.17
3 1 2011-03-15 2 2 2011-03-15 -0.03
4 2 2011-03-15 2
5 2 2011-03-16 1
我需要评估以下表达式,并仅使用SQL在quality
列中填写结果:
IF (class_value of tweet/return on that day) > 0 THEN quality = 1 ELSE 0
class_value为:
IF class = 1 THEN class_value = 0
IF class = 2 THEN class_value = 1
IF class = 3 THEN class_value = -1
对于每条推文,我需要(显然)接受该日期的股票回报。在周末期间,例如2011-03-16
,没有可用的库存数据。在这种情况下,quality
也应默认为0(并且不返回错误)。因此,让我们手动为示例中的4条推文执行此操作:
id class class_value return class_value/return quality
-----------------------------------------------------------
1 3 -1 0.44 -1/0.44 = -2.27 0
2 1 0 0.44 0/0.44 = 0 0
3 2 1 0.17 1/0.17 = 5.88 1
4 2 1 -0.03 1/-0.03 = -33.33 0
5 1 0 n/a 0
因此,查询的最终结果将是更新的tweets
表:
tweets
-------------------------------------
id stock_id nyse_date class quality
-------------------------------------
1 1 2011-03-12 3 0
2 1 2011-03-12 1 0
3 1 2011-03-15 2 1
4 2 2011-03-15 2 0
5 2 2011-03-16 1 0
我不知道如何将所有这些都放入查询中。我现在有了这个,但它只选择了类并返回但没有设置class_value
或实现表达式。
UPDATE tweets SET quality = (
SELECT t.class, s.return FROM tweets t
LEFT JOIN stocks s ON t.nyse_date = s._date
)
非常感谢任何帮助: - )
答案 0 :(得分:2)
update tweets
set quality = ifnull(case tweets.class
when 1 then 0
when 2 then 1
when 3 then -1
end
-- If there is no match, subquery will evaluate to null
-- Division will also evaluate to null
/ (select `return`
from stocks
where tweets.nyse_date = stocks._date
and tweets.stock_id = stocks.stock_id
)
-- If there was no match, quality = 0
, 0)
-- Shortcut to set 1 if condition is satisfied
-- If there is an error try encapsulating
-- whole expression into case when (ex) then 1 else 0 end
> 0
我想测试一下,因为我没有使用MySql,但我最喜欢的Sql Fiddle现在已经停止了。