MySQL每天按值排名

时间:2010-11-05 20:31:45

标签: sql mysql rank

我试图按700个符号每天的%回报排名。

例如:

date     symbol    pct_return
-----------------------------
1100101  IBM       1.2
1100101  AAPL      2.1
1100101  HPQ       -0.5

对于日期1100101,还有大约700个这样的条目

1100102  IBM       -.02
1100102  AAPL      -.6
1100102  HPQ       1.9

日期1100102

大约700个这样的条目

我要做的是创建一个查询或存储过程来循环每一天,然后排名并插入每天每个符号的百分比回报的排名值。

我想插入百分比回报的升序和降序排名值。

排名后只有3个符号的示例表如下所示:

date     symbol    pct_return    rank_asc   rank_desc
------------------------------------------------------
1100101  IBM       1.2             2         2
1100101  AAPL      2.1             3         1
1100101  HPQ       -0.5            1         3
1100102  IBM       -.02            2         2
1100102  AAPL      -.6             1         3
1100102  HPQ       1.9             3         1

3 个答案:

答案 0 :(得分:1)

您可以使用此语法在选择中选择行号:

SELECT @row := @row + 1 as row, t.*
FROM table t, (SELECT @row := 0) r;

然后,您可以选择每天ORDER BY升序和降序的所有值,并将它们插入到您的表格中。

来源:http://snippets.dzone.com/posts/show/6831

示例:

INSERT INTO [your table]
SELECT date, symbol, pct_return, @row := @row + 1
FROM [your other table] t, (SELECT @row := 0) r
ORDER BY pct_return ASC;

要获取升序值,请使用类似查询对同一个表进行更新以获取降序值。

答案 1 :(得分:0)

这是群内聚合的典型问题,通过左自我排除加入解决。

您不需要任何存储过程来获得所需的结果,只需一个简单的INSERT INTO ... SELECT ...查询即可。

以下是包含所提供数据的示例脚本:

CREATE TABLE shuffled_symbols ( 
   dat INT NOT NULL
  ,symbol VARCHAR(4) NOT NULL
  ,pct_return DECIMAL(4,2) NOT NULL
  ,PRIMARY KEY (dat ,symbol)
);
CREATE TABLE ranked_symbols ( 
   dat INT NOT NULL
  ,symbol VARCHAR(4) NOT NULL
  ,pct_return DECIMAL(4,2) NOT NULL
  ,rank_asc INT UNSIGNED NOT NULL
  ,rank_desc INT UNSIGNED NOT NULL
);

INSERT INTO shuffled_symbols (dat,symbol,pct_return) VALUES (1100101,'IBM',1.2);
INSERT INTO shuffled_symbols (dat,symbol,pct_return) VALUES (1100101,'AAPL',2.1);
INSERT INTO shuffled_symbols (dat,symbol,pct_return) VALUES (1100101,'HPQ',-0.5);
INSERT INTO shuffled_symbols (dat,symbol,pct_return) VALUES (1100102,'IBM',-0.02);
INSERT INTO shuffled_symbols (dat,symbol,pct_return) VALUES (1100102,'AAPL',-0.6);
INSERT INTO shuffled_symbols (dat,symbol,pct_return) VALUES (1100102,'HPQ',1.9);

以下是计算排名的查询(抱歉格式错误,我无法在<pre>标记内正确显示):

INSERT INTO ranked_symbols ( dat, symbol, pct_return, rank_asc, rank_desc ) SELECT ars.dat, ars.symbol, ars.pct_return, ars.rank_asc, COUNT(ss3.dat)+1 rank_desc FROM ( SELECT ss1.dat, ss1.symbol, ss1.pct_return, COUNT(ss2.dat)+1 rank_asc FROM shuffled_symbols ss1 LEFT JOIN shuffled_symbols ss2 ON ss2.dat = ss1.dat AND ss2.pct_return < ss1.pct_return GROUP BY ss1.dat, ss1.symbol ) ars LEFT JOIN shuffled_symbols ss3 ON ss3.dat = ars.dat AND ss3.pct_return > ars.pct_return GROUP BY ars.dat, ars.symbol ;

请注意,如果您没有给定日期的重复符号,此查询将仅返回有效排名。这就是我用shuffled_symbols创建PRIMARY KEY (dat ,symbol)表的原因。

在ranking_symbols表中,您会得到以下结果:

SELECT * FROM ranked_symbols;

+---------+--------+------------+----------+-----------+
| dat     | symbol | pct_return | rank_asc | rank_desc |
+---------+--------+------------+----------+-----------+
| 1100101 | AAPL   |       2.10 |        3 |         1 |
| 1100101 | HPQ    |      -0.50 |        1 |         3 |
| 1100101 | IBM    |       1.20 |        2 |         2 |
| 1100102 | AAPL   |      -0.60 |        1 |         3 |
| 1100102 | HPQ    |       1.90 |        3 |         1 |
| 1100102 | IBM    |      -0.02 |        2 |         2 |
+---------+--------+------------+----------+-----------+
6 rows in set (0.00 sec)                                

答案 2 :(得分:0)

  

以下是我对布伦特的扩展   PERL的例子。这非常   对我很有帮助,我非常感激   社区支持。

从命令行运行代码:

rank.pl FromTableNoRank ToTableWithRank pct_return DESC

#!/usr/bin/perl -w

use strict;
use warnings;
use Carp;

// connect to database here

// Not enough command-line arguments, helpful error message.
if(@ARGV!=4) {
    die("$0 requires four arguments. 1.FromTable 2.ToTable 3.Order by value(ex.pct_return) 4.ASC (low = 1) or DESC(high = 1)\n");
}

// Use variables for insert to minimize errors
// $OrderBy is the value to rank 
// $AscDesc declares which way to rank
my $FromTable = $ARGV[0];
my $ToTable   = $ARGV[1];
my $OrderBy   = $ARGV[2];
my $AscDesc   = $ARGV[3];


// DateTable is table of dates for use within the insert query. Used to loop through and rank individual days.
my $query7 = "SELECT dat FROM DateTable ORDER BY dat ASC";
my $sth7   = $dbh->prepare($query7) || carp DBI::errstr;
$sth7->execute() || carp DBI::errstr;

// Fetchrow_hashref holds all dates from date tables and while loop walks through one at a time
// The insert sorts by a value and then a row number is added to provide a rank of values
// The nested sth exists because need to reference $dateVar from fetchrow
while(my $ref = $sth7->fetchrow_hashref()) {
    my $dateVar = $ref->{dat};
    print "$dateVar \n";
    my $query6 = "INSERT INTO $ToTable 
        SELECT t.*,". '@rownum := @rownum +1' . " 
        FROM $FromTable t, ".'(SELECT @rownum := 0) r  
        WHERE dat ='."$dateVar
        ORDER BY $OrderBy $AscDesc";
    my $sth6 = $dbh->prepare($query6) || carp DBI::errstr;
    $sth6->execute() || carp DBI::errstr;
    $sth6->finish();
}

$sth7->finish();
$dbh->disconnect();