选择与具有特定值的其他行关联的行

rbl8hiat  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(284)

我有一些关于电话的数据,这些数据以事件的形式出现,类似于:

|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 最后,通过选择具有 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|
oxosxuxt

oxosxuxt1#

我会用 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');
ctrmrzij

ctrmrzij2#

在子查询中,确定所有 call_id 至少有一行包含 service = 'SALES' .
只需在外部查询中使用此子查询结果进行匹配 call_id 得到所有 event_id
方法1:使用派生表

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')

ryevplcw

ryevplcw3#

好的,我想你要找的是如下的东西。我用过 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)

相关问题