我以事件的形式获取有关电话的数据,如下所示:
|event_id|call_id|event_type |service|...
|--------|-------|----------------|-------|---
| 1| 1|Call Started |null |
| 2| 1|Recorded Message|null |
| 3| 1|Call at IVR |null |
| 4| 1|Agent Ringing |Sales |
| 5| 1|Agent Answers |Sales |
| 6| 2|Call Started |null |
| 7| 2|Recorded Message|null |
| 8| 2|Call at IVR |null |
| 9| 1|Disconnected |null |
| 10| 1|Call Ended |null |
| 11| 3|Call Started |null |
| 12| 3|Recorded Message|null |
| 13| 2|Agent Ringing |Support|
| 14| 3|Agent Ringing |Sales |
| 15| 2|Agent Answers |Support|
| 16| 3|Agent Answers |Sales |
| 17| 3|Call Hold |null |
| 18| 2|Disconnected |null |
| 19| 2|Call Ended |null |
| 20| 3|Call Retrieved |Sales |
| 21| 3|Disconnected |null |
| 22| 3|Call Ended |null |
我只想选择与调用Sales
相关的那些事件。如您所见,service
列中仅包含某些类型的事件,这是我需要过滤的列。由于处理方式的差异,呼叫在包含的事件数量上也不一致。
我一直在通过加载所有事件来过滤应用程序中的调用,然后在GroupBy()
上使用call_id
并最终通过选择任何具有 any 事件的组来过滤这些组service
等于Sales
。
由于实际数据中有大量我不想要的调用,因此在数据库中进行过滤会更有效。我该怎么办?
类似
SELECT event_id
FROM events
GROUP BY call_id
HAVING (SELECT COUNT(*) FROM ***this_group*** WHERE service='Sales') > 0
预期输出应为
|event_id|
|--------|
| 1|
| 2|
| 3|
| 4|
| 5|
| 9|
| 10|
| 11|
| 12|
| 13|
| 16|
| 17|
| 20|
| 21|
| 22|
答案 0 :(得分:2)
call_id
值,其中至少有一行包含service = 'SALES'
。call_id
并获取所有event_id
值方法1 :使用Derived Table
SELECT e1.event_id
FROM events AS e1
JOIN (SELECT DISTINCT e2.call_id
FROM events AS e2
WHERE e2.service = 'SALES') AS dt
ON dt.call_id = e1.call_id
方法2 :使用WHERE .. IN(..)
SELECT e2.event_id
FROM events AS e2
WHERE e2.call_id IN (SELECT DISTINCT e1.call_id
FROM events AS e1
WHERE e1.service = 'SALES')
答案 1 :(得分:2)
我会使用EXISTS
:
SELECT e1.event_id
FROM events e1
WHERE EXISTS (SELECT 1 FROM events e2 WHERE e2.call_id = e1.call_id AND e2.service = 'SALES');
答案 2 :(得分:0)
好的,我想您正在寻找的是类似以下内容的东西。我使用过WITH
查询来挑选您要查找的呼叫,并使用第二个查询来挑选这些呼叫中的事件。
WITH salesCalls AS (
SELECT call_id, event_type, service
FROM events
WHERE event_type = "Agent Answers"
AND service = "Sales"
GROUP BY call_id, event_type, service
);
SELECT event_id
FROM events
WHERE call_id IN (SELECT call_id FROM salesCalls)