2010-10-27 102 views
3

我已搜索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天才能夠通過我的方式。

回答

2

與威爾基女士的電子郵件交談後,原來她想這樣的變化百分比:

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

完美!完善!完善!完善!完善!完善! ..再次感謝唐!珍妮 – 2010-11-01 14:20:08

0

從樣本數據我假設記錄不是「更新」,而是插入新記錄。

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是表的名稱 - 與實際值進行替代)

+0

謝謝葉蘭!這是一個好的開始,我真的很感謝你的幫助。 JW – 2010-10-27 12:30:52

1

它是一個有點古怪,因爲做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

+0

唐,你是一位聖人,我很欣賞這種幫助。 JW – 2010-10-27 12:31:22

+0

我已經接受了這個答案,它完全按照指示工作。 – 2010-11-01 14:18:50