mysql - 引用上面的单元格

标签 mysql cell

我需要有关引用上述单元格的 mysql 查询的帮助。
例如,在下表中:

primary key(id)     day             count           percentage change
1                  monday             1               0  
2                  tuesday            2              (1-0)*100%=100%  
3                  wednesday          5              (2-1)*100%=100%  
4                  thursday           9              (5-2)*100%=300%  
5                  friday             27             (9-5)*100%=400%  

百分比变化结果是基于count列前两天的结果。有没有办法合并主键(id)来引用“上面”的单元格?

最佳答案

没有简单的方法。您需要使用自联接。

select t.*,
       (coalesce(t_1.count, 0) - coalesce(t_2.count, 0)) * 100.0
from t left outer join
     t t_1
     on t.id = t_1.id + 1 left outer join
     t t_2
     on t.id = t_2.id + 2

left outer join 确保保留所有原始行,即使没有前面的 id。

之所以可行,是因为 ID 是连续的。如果 ID 不是连续的,并且计数是单调递增的,则可以使用相关子查询来执行此操作:

select t.*,
       (coalesce((select max(`count`) as val
                  from table1 t_1
                  where t_1.`count` < t.`count`
                 ), 0)
       ) -
       (coalesce((select max(`count`)
                  from table1 t_2
                  where t_2.`count` < (select max(`count`) from table1 t_1 where t_1.`count` < t.`count`)
                 ), 0)
       )
from table1 t

注意:如果一行中的两个值相同,这将无法正常工作。为此,您需要改用 id:

select t.*,
       (coalesce((select max(`count`) as val
                  from table1 t_1
                  where t_1.`id` < t.`id`
                 ), 0)
       ) -
       (coalesce((select max(`count`)
                  from table1 t_2
                  where t_2.`id` < (select max(`id`) from table1 t_1 where t_1.`id` < t.`id`)
                 ), 0)
       )
from table1 t

如果计数没有增加,则必须获取 id,然后重新加入值。多么有趣!这是代码:

select t.*,
       coalesce(t1.count, 0) - coalesce(t2.count, 0)
from (select t.*,
             (select max(`id`) as id1 from table1 t_1 where t_1.`id` < t.`id`
             ) as id1,
             (select max(`count`) from table1 t_2
              where t_2.`id` < (select max(`id`) from table1 t_1 where t_1.`id` < t.`id`)
             ) id2
      from table1 t
     ) t left outer join
     table1 t1
     on t.id1 = t1.id left outer join
     table1 t2
     on t.id2 = t2.id

关于mysql - 引用上面的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11958719/

相关文章:

mysql - SQL中的SQL连接和子查询

mysql - 无法从 Cloud Foundry 应用程序连接到 mySQL 数据库

mysql - Docker:使用来自主机的--net = host选项访问docker容器中的mysql

php - 代码仅更新数据库中的 false 值,但不更新 true 值

java - Vaadin - 突出显示表格选定的单元格/行

ios - 单元格如何为 UITableView 删除

MySql 外键索引

Javascript将按钮添加到表中的下一行

ios - 如何在单元格中设置视频的缩略图

ios - UICollectionView 单元格 UI 水平分页随机消失