首页 > 解决方案 > 如何将变量传递给子查询?

问题描述

我有一个包含 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%

标签: mysqlsql

解决方案


也许你只是想要这样的东西

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)

推荐阅读