gpt4 book ai didi

MySQL减去两个计数列

转载 作者:可可西里 更新时间:2023-11-01 06:46:50 26 4
gpt4 key购买 nike

我有一个这样的表:

client    msg_type   msg_body  id
------ -------- -------- ---
123 typeA success abc
123 typeB success abc
456 typeA success abc
456 typeB failure abc
123 typeA success abc
123 typeA success abc
789 typeA success def
789 typeB success def

等等

我想要这样的输出:

client    diff   id
------ ---- ---
123 2 abc
456 1 abc
789 0 def

其中 difftypeA:success 消息的计数 - typeB:success 消息。我可以使用类似的方法获得 typeA 成功的计数:

select client, count(*) from mytable
where msg_type="typeA" and msg_body="success"

但是,我无法弄清楚如何在其中添加另一个计数(对于类型 B)并进行减法。我试过类似的东西:

select client, count(*) from mytable
where msg_type="typeA" and msg_body="success" - count(*)
from mytable where msg_type="typeB" and msg_body="success"

不过当然不行,不然我也不会在这里问了。 :) 有什么建议吗?

编辑:添加了另一列。我尝试了给出的两个建议,但它似乎只返回其中一个 ID 的结果,而不是两个。

编辑 #2:我尝试用以下方式包装 SELECT 查询:

select id, count(*) from (select ...) as anothertable where count_a_minus_count_b = 0;

我希望输出是这样的:

id    count
--- -----
abc 2
def 1

其中 count 是 typeA:success 和 typeB:success 之差为 0 的客户端数。

最佳答案

COUNT 计算非空值,因此您可以在 msg_type = 'typeA' 时构造一个非空表达式,在 msg_type = 'typeB'。例如:

SELECT client,
COUNT(CASE WHEN msg_type = 'typeA' THEN 1 END) AS count_a,
COUNT(CASE WHEN msg_type = 'typeB' THEN 1 END) AS count_b,
COUNT(CASE WHEN msg_type = 'typeA' THEN 1 END)
- COUNT(CASE WHEN msg_type = 'typeB' THEN 1 END) AS count_a_minus_count_b
FROM mytable
WHERE msg_body = 'success'
GROUP
BY client
;

(免责声明:未经测试。)

关于MySQL减去两个计数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18345909/

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