我有一个包含 5 个文本数据类型日期时间的数据库。这些值为 4/15/12 1:47
(类型 FT)、9/8/12 20:02
(类型 FT)、5/10/13 22:21
(类型 FT)、3/3/13 4:46
(类型 FT)和 2/9/12 4:19
(类型 NL)。我想计算每小时发生的事件数,然后除以事件总数。
由于该列采用文本数据类型,因此我使用以下代码选择小时:hour(str_to_Date(order_placer_placed_time,'%m/%d/%Y %H:%i')
.
我尝试过的代码是
select (
(select count(*) from col where type = 'ft' and hour(str_to_Date(time,'%m/%d/%Y %H:%i')) = 4
group by type)
/count(*)) as 'FT %',
hour(str_to_Date(time,'%m/%d/%Y %H:%i')) as hour
from col
group by hour
order by hour;
我需要将子查询中的 4
更改为每天的所有小时段,这样我就可以返回一个结果,显示“ft”个体的百分比除以总个体数。
我不确定如何使子查询中的 4
动态化以返回我正在查找的结果。
最终输出应如下所示:
1 100%
4 50%
20 100%
22 100%
最佳答案
也许你只是想要这样的东西
drop table if exists col;
create table col
(type varchar(3),ts varchar(20));
insert into col values
('ft','1/2/2019 1:47'),('ft','1/2/2019 20:02'),('ft','1/2/2019 22:21'),('ft','1/2/2019 1:47'),('ft','1/2/2019 4:19'),
('ft','1/3/2019 1:47'),('nl','1/3/2019 4:19');
select hour(str_to_Date(ts,'%m/%d/%Y %H:%i')) as hour,
sum(case when type = 'ft' then 1 else 0 end) obsft,
count(*) obsall,
sum(case when type = 'ft' then 1 else 0 end) /
count(*) * 100 as perft
from col
group by hour(str_to_Date(ts,'%m/%d/%Y %H:%i'))
union
select 25,
sum(case when type = 'ft' then 1 else 0 end) obsft,
count(*) obsall,
sum(case when type = 'ft' then 1 else 0 end) /
count(*) * 100 as perft
from col;
+------+-------+--------+----------+
| hour | obsft | obsall | perft |
+------+-------+--------+----------+
| 1 | 3 | 3 | 100.0000 |
| 4 | 1 | 2 | 50.0000 |
| 20 | 1 | 1 | 100.0000 |
| 22 | 1 | 1 | 100.0000 |
| 25 | 6 | 7 | 85.7143 |
+------+-------+--------+----------+
5 rows in set (0.00 sec)
关于mysql - 如何将变量传递到子查询中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56161860/