mysql - 如何将变量传递给子查询?
问题描述
我有一个包含 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)
推荐阅读
- java - 将列表对象与其他对象排序
- java - 确保所有线程更新 Java 映射中的单个条目
- javascript - 无法使用 Array.sort 在 JavaScript 中实现正确的排序
- mysql - rails - 我错误地运行了“rake db:drop”。我怎样才能恢复我的所有数据?
- amazon-web-services - AWS s3 将多个文件夹同步到不同的目的地
- macros - 如何检测应用程序何时在 Bluestacks 上崩溃
- java - 匿名 AsyncTask 中的构造函数,例如“new AsyncTask
()”? - c# - 如何从选中的列表框中检索数据并在 datagrideview 中显示数据?
- c# - OxyPlot - 光标
- r - 计算列表中每个 data.frame 中的行数