用于更新百分比更改的SQL语句
我已搜索S.O.这个答案已经接近答案,但仍然不够接近。我有兴趣知道MySQL是否具备这种能力。用于更新百分比更改的SQL语句
我已经开发了Perl和MySQL 4,现在我在MySQL 4上。 我的表看起来像这样...
- 符号VARCHAR(25)
- todayDate日期
- 兴趣INT(11)
我的问题是这样的.....这些符号(约20万人)每天更新一次兴趣领域的新号码。
一个例子是这个....
symbol | todayDate | interest
-------------------------------
A202015 | 2010-10-26 | 150
A202015 | 2010-10-25 | 100
理想的情况下我会能够做到将在与前一次记录的百分比变化最终更新另一个领域。以上将看起来像这样......
symbol | todayDate | interest | change
-----------------------------------------
A202015 | 2010-10-26 | 150 | 50
A202015 | 2010-10-25 | 100
我没想到这个功能在MySQL中是可行的。我得出结论,我只需要抓住以前的记录信息,做数学计算,然后用百分比信息更新最新的记录。我只是想我会仔细检查一下,看看有没有什么MySQL天才能够通过我的方式。
与威尔基女士的电子邮件交谈后,原来她想这样的变化百分比:
update t_test_1 as t1
set chng = (t1.interest - (
select interest from (
select *
from t_test_1 as t11
) as x
where x.symbol = t1.symbol and x.todayDate < t1.todayDate
order by x.todayDate desc
limit 1
))/
(
select interest from (
select *
from t_test_1 as t11
) as x2
where x2.symbol = t1.symbol and x2.todayDate < t1.todayDate
order by x2.todayDate desc
limit 1
) * 100 ;
从样本数据我假设记录不是“更新”,而是插入新记录。
INSERT INTO `rates` (`symbol`,`todayDate`,`interest`,`change`)
SELECT symbol,CURDATE(),$interest,$interest - `interest`
FROM `rates`
WHERE `symbol`='$symbol' AND `todayDate` = CURDATE() - INTERVAL 1 DAY
($兴趣和$符号是包含您要插入的值的变量,rates
是表的名称 - 与实际值进行替代)
谢谢叶兰!这是一个好的开始,我真的很感谢你的帮助。 JW – 2010-10-27 12:30:52
它是一个有点古怪,因为做MySQL引用的子查询,但这会做你需要什么,我想:
/*
create table t_test_1 (
symbol varchar(20) not null,
todayDate datetime not null,
interest int not null,
chng int null
)
*/
insert into t_test_1 (symbol, todayDate, interest, chng) values ('A202015', '2010-10-09', 90, null);
insert into t_test_1 (symbol, todayDate, interest, chng) values ('A202015', '2010-10-10', 80, null);
insert into t_test_1 (symbol, todayDate, interest, chng) values ('A202015', '2010-10-11', 120, null);
update t_test_1 as t1
set chng = t1.interest - (select interest from (
select *
from t_test_1 as t11
) as x
where x.symbol = t1.symbol and x.todayDate < t1.todayDate
order by x.todayDate desc
limit 1
);
select * from t_test_1;
这导致:
A202015 2010-10-09 90 NULL
A202015 2010-10-10 80 -10
A202015 2010-10-11 120 40
哦,我应该补充说,这是针对MySQL 5.x数据库服务器的。我不确定它是否会对4.x起作用,因为我没有4.x服务器来测试,对不起。
-don
唐,你是一位圣人,我很欣赏这种帮助。 JW – 2010-10-27 12:31:22
我已经接受了这个答案,它完全按照指示工作。 – 2010-11-01 14:18:50
完美!完善!完善!完善!完善!完善! ..再次感谢唐!珍妮 – 2010-11-01 14:20:08