3

我有两个表,我想获取百分比值并将百分比更新到表中。假设我们有两个这样的表,

表格1

   date     open   high   low   close   stock_id
2013-01-02   10     20     5     15        1
2013-01-02   150    200   100    170       2
2013-01-03   15     30     10    20        1

表 2

   date     p_high  p_low   percent   stock_id
2013-01-02   25     10       0.00        1
2013-01-02   210    120      0.00        2
2013-01-03   40     20       0.00        1

我想用这个公式计算百分比

(p_high - high) / high

stock_id = 1in 的百分比date = 2013-01-02将是这样的。

(25 - 20) / 20 = 25.00

当我得到百分比时,我想将它更新到表 2,所以它会是这样的,

  date      p_high   p_low   percent   stock_id
2013-01-02    25      10      25.00       1

我怎么能在mysql中做到这一点?

感谢您的帮助。

4

2 回答 2

1

当然可以,请查看http://sqlfiddle.com/#!2/61c460/2

UPDATE Table2 t2
INNER JOIN Table1 t1 ON t2.stock_id = t1.stock_id AND t1.date = t2.date 
SET 
    t2.percent = (t2.p_high - t1.high) / t1.high;

Sqlfiddle 将不允许更新,但如果您获得查询并在 mysql 中运行,它将起作用。

同一股票和日期可以有多个条目吗?

于 2013-04-18T10:07:29.543 回答
1

DDL

create table table1(
    created_dt date,
    open decimal(5,2),
    high decimal(5,2),
    low decimal(5,2),
    close decimal(5,2),
    stock_id integer
);

create table table2(
    created_dt date,
    p_high decimal(5,2),
    p_low decimal(5,2),
    percent decimal(5,2),
    stock_id integer
);

DML

insert into table1 values ('2013-01-02',10,20,5,15,1);
insert into table1 values ('2013-01-02',150,200,100,170,2);
insert into table1 values ('2013-01-03',15,30,10,20,1);

insert into table2 values('2013-01-02',25,10,0.00,1);
insert into table2 values('2013-01-02',210,120,0.00,2);
insert into table2 values('2013-01-02',40,20,0.00,1);

update table2
join table1
on table1.created_dt = table2.created_dt and table1.stock_id = table2.stock_id
set percent = ((p_high - high)/high);

工作示例 http://sqlfiddle.com/#!2/21d02/1/0

于 2013-04-18T10:18:08.343 回答