mysql - Excel转Mysql查询
解决方案
给定
drop table if exists t;
create table t(dt date,cola int,colb int);
insert into t values
(str_to_date('29/10/2020','%d/%m/%Y'),147,150),
(str_to_date('30/10/2020','%d/%m/%Y'),160,170),
(str_to_date('01/11/2020','%d/%m/%Y'),170,170),
(str_to_date('02/11/2020','%d/%m/%Y'),180,170),
(str_to_date('03/11/2020','%d/%m/%Y'),190,170);
您可以使用相关子查询来获取从当前行到列末尾的总计
select t.*,
(select sum(cola) from t t1 where t1.dt >=t.dt) sumcola,
(select sum(colb) from t t1 where t1.dt >=t.dt) sumcolb,
(select sum(colb) from t t1 where t1.dt >=t.dt) /
(select sum(cola) from t t1 where t1.dt >=t.dt) kpi
from t;
或者如果您有版本 8 或更高版本
select t.*,
sum(cola) over (order by dt rows between current row and unbounded following) sumcola,
sum(colb) over (order by dt rows between current row and unbounded following) sumcolb,
sum(colb) over (order by dt rows between current row and unbounded following) /
sum(cola) over (order by dt rows between current row and unbounded following) kpi;
from t;
+------------+------+------+---------+---------+--------+
| dt | cola | colb | sumcola | sumcolb | kpi |
+------------+------+------+---------+---------+--------+
| 2020-10-29 | 147 | 150 | 847 | 830 | 0.9799 |
| 2020-10-30 | 160 | 170 | 700 | 680 | 0.9714 |
| 2020-11-01 | 170 | 170 | 540 | 510 | 0.9444 |
| 2020-11-02 | 180 | 170 | 370 | 340 | 0.9189 |
| 2020-11-03 | 190 | 170 | 190 | 170 | 0.8947 |
+------------+------+------+---------+---------+--------+
5 rows in set (0.001 sec)
推荐阅读
- node.js - 如何处理猫鼬测试中的 Schema.save 延迟
- r - 超参数调优一类SVM
- python - python练习的切片和范围
- python - vcbuild 不起作用 - 无法确定 Node.js 的当前版本 - 在 Windows 上构建节点存储库
- html - 在网格布局中将单行独立成列
- azure - 访问 Azure B2C 身份时访问电子邮件(使用成员用户)
- javascript - 为什么我无法访问对象属性?
- javascript - 计算“字符串”类型的深层嵌套对象属性
- tensorflow - 为什么每次运行自动编码器时,编码数据帧中的值都会不稳定?
- ios - OverrideUserInterfaceStyle 和 willTransition 在其他类中不起作用