计算在同一列中具有两个不同值的结果

时间:2013-09-11 21:48:34

标签: mysql sql

我在支持工作,我正在计算有多少'案例'已应用这两个标签:

'聊天'并且' Escalated'

这是我正在使用的查询,但我的号码不正确:

    select count(pk_case_number)
    from cases c
    join labels l
    on l.case_number = c.case_number
    where lower(label_name) = 'chat' 
    and exists (select distinct case_number
    from cases c
    join labels l
    on on l.case_number = c.case_number
    where l.case_number = c.case_number
    and lower(label_name) = 'escalated')
    and date(created_at) > '2013-08-11' 

' created_at'在案例表中。

1 个答案:

答案 0 :(得分:1)

以下查询列出了条件为真的所有情况:

select pk_case_number
from cases c join
     labels l
     on l.case_number = c.case_number
group by pk_case_number
having sum(lower(label_name) = 'chat') > 0 and
       sum(lower(label_name) = 'escalated') > 0;

以下计算它们:

select count(*)
from (select pk_case_number
      from cases c join
           labels l
           on l.case_number = c.case_number
      group by pk_case_number
      having sum(lower(label_name) = 'chat') > 0 and
             sum(lower(label_name) = 'escalated') > 0
     ) t

我喜欢使用聚合和having子句进行这些类型的查询,因为我发现它是最通用的。可以轻松添加所需的新标签或排除特定标签(使用= 0而不是> 0)。