I work in support and I am trying to count how many 'cases' have both of these labels applied:
'Chat' and 'Escalated'
This is the query I am using, but I am getting an incorrect number:
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' is in the cases table.
The following query lists all the cases where the condition is true:
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;
The following counts them:
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
I like doing these sorts of queries with aggregation and the having
clause, because I find that to be the most general. It is easy to add new labels that are required or to exclude a particular label (use = 0
rather than > 0
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.