mysql - 查找表中与当前行匹配的前一行

标签 mysql r matlab

我有一个篮球数据集,其中 A 列代表不同的球队。有没有一种好方法可以提取该数据集中的最后几行,例如 A 列与“勇士”匹配的行?

我在这里的意思是我想找到当前行之前的最后 3 行,其中 A 列表示“勇士队”。我该如何在 R(或 SQL 或 Matlab)中执行此操作?

最佳答案

我可以在 Matlab 中提出一个解决方案。

为了演示,我首先创建一个包含单列 A 的随机表:

T = 

          A       
    ______________

    'The Warriors'
    '43'          
    '38'          
    '40'          
    '49'          
    '71'          
    '69'          
    '64'          
    '67'          
    'The Warriors'
    'The Warriors'
    'The Warriors'
    '131'         
    'The Warriors'
    '119'         
    '124'         
    '93'          
    '109'         
    '77'          
    'The Warriors'
    '83'          
    '117'         
    '75'          
    '122'         
    '80'          
    'Smith'       
    'Johnson'     
    'Williams'    
    'Jones'       
    'Brown' 

现在,如果第 i 行包含字符串 'The Warriors',则可以创建一个 bool 向量,其中在位置 i 处包含 true (1) :

matchresult=cellfun(@(x) strcmp(x,'The Warriors'),T.A);

事实上,现在 matchresult 具有以下形式:

matchresult =

     1
     0
     0
     0
     0
     0
     0
     0
     0
     1
     1
     1
     0
     1
     0
     0
     0
     0
     0
     1
     0
     0
     0
     0
     0
     0
     0
     0
     0
     0

现在我们可以扫描这个向量而不是整个表来查找最后 3 行:

for i=4:length(matchresult)                 % since we want 3 rows we can start scanning from the 4th
    if(sum(matchresult(1:i-1))>=3)          % if there are at least 3 ones in previous rows
        fprintf('Scanning row #%d:\n',i);   % see the row index we're scanning
        find(matchresult((1:i-1)),3,'last') % find 1s in previous rows and display last 3 indices
    end
end

关于mysql - 查找表中与当前行匹配的前一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36740120/

相关文章:

mysql - 大表 In 运算符 MySql

java.sql.SQLException 参数索引超出范围(1 > 参数数量,即 0)

R 重新编码变量 - 意外的 INCOMPLETE_STRING

根据一组条件用其他数据框中的值替换数据框中的值

r - 将数据框中许多列的类从因子更改为数值

path - 如何更新 MATLAB 路径?

matlab - 在 Matlab 中生成 64 位随机整数

php - 如何从 mysql 获取列名?

MATLAB XYZ 到网格

php - 检查数据库中是否存在行,如果不存在则显示消息