mysql - 如何在 mysql 中旋转 mysql 中的上一个日期
问题描述
表结构和数据位于https://www.db-fiddle.com/f/5rKXiavsoMeQazSHwxaTVK/0
我正在尝试获取所有先前日期范围的百分比。
circle_name`|current_capacity|2020-03-16|2020-03-17|2020-03-18|
其中当前容量是最大日期容量和每个日期在行中的百分比。
最终结果像https://www.db-fiddle.com/f/wTFejVRzQBTXZkfWjBuqq8/0
select circle_name,Subscriber as current_capacity,
Subscriber/Subs_Capacity * 100 as percentage,
DATE_FORMAT(date,'%y-%m-%d') as date
from circle
where date BETWEEN date_add('2020-03-18',interval -3 day)
and '2020-03-18'
请在 mysql 中提供帮助。
解决方案
这是一种使用条件聚合的方法。这不是将实际日期分配给列名(这将需要动态 SQL),而是通过设置一个变量来表示您希望计算开始的日期,然后生成名为的列d_2
(对于day - 2)d_1
和d_0
.
set @mydate = '2020-03-18';
select
circle_name,
max(case when date = @mydate then subscriber end) current_capacity,
100 * sum(case when date = @mydate - interval 2 day then subscriber end)
/ sum(case when date = @mydate - interval 2 day then subs_capacity end) d_2,
100 * sum(case when date = @mydate - interval 1 day then subscriber end)
/ sum(case when date = @mydate - interval 1 day then subs_capacity end) d_1,
100 * sum(case when date = @mydate then subscriber end)
/ sum(case when date = @mydate then subs_capacity end) d_0
from circle
group by circle_name;
在您的 db fiddle中,查询产生:
| circle_name | current_capacity | d_2 | d_1 | d_0 |
| ----------- | ---------------- | ------- | ------- | ------- |
| AP | 758415 | 90.8422 | 91.1373 | 91.3753 |
| AS | 764976 | 83.461 | 83.2508 | 82.7001 |
| BH | 807447 | 84.5168 | 86.2083 | 85.8986 |
| CH | 785384 | 87.4384 | 87.2934 | 87.2649 |
| DL | 859161 | 85.9683 | 85.5766 | 85.9161 |
| GJ | 882817 | 85.6419 | 85.7533 | 86.1285 |
| HP | 203300 | 80.9292 | 80.9608 | 81.32 |
| HR | 255511 | 84.9163 | 85.1213 | 85.1703 |
| JK | 592271 | 84.244 | 84.2937 | 84.6101 |
| KK | 729628 | 88.0607 | 88.1499 | 87.907 |
| KL | 793872 | 80.0359 | 79.5544 | 79.3872 |
| KO | 847638 | 84.6341 | 84.6501 | 84.7638 |
| MB | 687501 | 87.8208 | 85.9449 | 85.9376 |
| MH | 886554 | 95.8487 | 95.6997 | 88.6554 |
| MP | 821474 | 83.1335 | 83.3047 | 83.8239 |
| NE | 824807 | 87.5708 | 87.5969 | 86.8218 |
| OR | 710822 | 84.5128 | 85.2319 | 83.6261 |
| PB | 194300 | 88.798 | 96.5235 | 97.15 |
| RJ | 840310 | 82.438 | 83.7309 | 84.031 |
| TN | 725307 | 90.8855 | 90.7334 | 90.6634 |
| UE | 903366 | 89.8577 | 90.0483 | 90.3366 |
| UW | 729154 | 98.9529 | 87.1339 | 87.8499 |
| WB | 0 | 0 | 0 | 0 |
推荐阅读
- python - 如何使用正则表达式 python 部分搜索单词
- android - Android AppCompActivity 工具栏未显示
- openmaptiles - 192天打造欧式瓷砖
- python - Python 中的 BrokenPipeError 但在 Perl 中没有
- python - 根据pandas中另一列中不同数组中元素的值获取列中数组的元素
- core-data - 未显示折线图数据
- r - lapply 如果在 data.table 中
- html - 仅针对较窄的屏幕修改内部 href 链接
- localization - 将 System.Globalization.DateTimeFormatInfo 短日期格式转换为 Windows.Globalization.DateTimeFormatting.DateTimeFormatter
- delphi - 在 Delphi 中更改单元的初始化顺序