gpt4 book ai didi

mysql - 如何划分单个列中的值并将结果存储在 MySQL 中的另一列中

转载 作者:行者123 更新时间:2023-11-29 02:48:30 24 4
gpt4 key购买 nike

我有一个名为“警报”的表,看起来像这样。

user_id event   alert_type
1 imp s
2 imp b
3 imp b
3 clk b
6 imp b
9 imp s
9 clk s
2 clk b
6 clk b
17 imp p
18 imp p
19 imp s
11 imp b
14 imp s
1 clk s
11 clk b
15 imp p
15 clk p
20 imp b
21 imp b
22 imp p
23 imp s
24 imp s
23 clk s
18 clk p
29 imp b
29 clk b
16 imp p
16 clk p
27 imp s
28 imp s

我正在尝试为每个 alert_type 创建一个名为 result 的新列,其中 result = clk/imp

我想要的输出是

alert_type  result
b 0.7143
p 0.6
s 0.375

我正在尝试这样做,但我知道这是非常低效的。

select 
((select alert_type,count(*) from alerts where alert_type = 'b' and event = 'clk') /
(select alert_type,count(*) from alerts where alert_type = 'b' and event = 'imp')) result
from dual;

请帮助我以简洁的方式实现所需的输出。

最佳答案

你可以尝试这样的事情:

SELECT 
alert_type,
(SUM(`event` = 'clk' ) / SUM(`event` = 'imp')) AS result
FROM alerts
WHERE alert_type ='b'
GROUP BY alert_type

注意:

由于 MySQL bool 表达式解析为 0/1,因此您可以在您的用例中将其大写。

SUM(a=b) 仅当 a 等于 b 时返回 1

更多:由于我使用的是 SUM 而不是 COUNT 所以你不必担心 DIVIDE BY ZERO 错误。

关于mysql - 如何划分单个列中的值并将结果存储在 MySQL 中的另一列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38938817/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com