【发布时间】:2013-08-20 22:21:41
【问题描述】:
我有一张这样的桌子:
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
其中diff 是typeA:success 消息的计数 - typeB:success 消息。我可以使用以下方法获得 typeA 成功的计数:
select client, count(*) from mytable
where msg_type="typeA" and msg_body="success"
但是,我不知道如何在其中添加另一个计数(对于 typeB)并减去。 我试过类似的东西:
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 的客户端数。
【问题讨论】:
-
回复:“我尝试了给出的两个建议,但它似乎只返回其中一个 id 的结果,而不是两者”:所有答案都显示了如何计算计数之间的差异;我认为他们都非常清楚。与其简单地尝试建议而不阅读它们,我建议您尝试从中学习,如果有不明白的部分,请提出问题。 :-/
-
@ruakh 我以为我理解我正在运行的查询,因此我尝试不同的事情。我想我明白了: select id, count(*) from (SELECT id, client, 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) as sometable where count_a_minus_count_b