0

我在支持工作,我试图计算有多少“案例”同时应用了这两个标签:

“聊天”和“升级”

这是我正在使用的查询,但我得到的数字不正确:

    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”在案例表中。

4

1 回答 1

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)很容易。

于 2013-09-11T21:55:26.840 回答