首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >参考上面的单元格

参考上面的单元格
EN

Stack Overflow用户
提问于 2012-08-15 02:43:00
回答 1查看 85关注 0票数 1

我想帮助mysql查询,引用上面的单元格。

例如,在下表中:

代码语言:javascript
运行
复制
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)来引用“上面”的单元格?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-15 02:54:58

没有一种简单的方法。您需要使用自连接。

代码语言:javascript
运行
复制
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

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

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

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
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

如果计数没有增加,那么您必须获取ids,并再次加入这些值。太好了!代码如下:

代码语言:javascript
运行
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11958719

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档