如何将变量传递给子查询?

时间:2019-05-16 06:12:24

标签: mysql sql

我有一个数据库,其中有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%

1 个答案:

答案 0 :(得分:2)

也许您只想要这样的东西

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)
相关问题