SQL:获取具有尚未完成的“工作请求”的帐户列表

时间:2017-04-03 15:06:34

标签: sql

我想提出一个查询,该查询会获得一个尚未完成“工作请求”的帐户列表。

我在下面的查询为我提供了“工作请求”“已收到”和“已完成”的所有帐户,但我只希望收到更多次完成的帐户。

SELECT n.incident_no,
   e.event_sub_type,
   COUNT (*) qty
FROM tb_event e,
 tb_incident n,
 vius_def d
WHERE e.incident_id = n.incident_id
 AND n.incident_id = d.incident_id
 AND EXISTS
 (SELECT 0
 FROM TB_EVENT e
 WHERE e.event_type = 'wrk req'
   AND e.event_sub_type = 'received'
   AND e.incident_id = n.incident_id)
AND EXISTS
(SELECT 0
 FROM TB_EVENT e
 WHERE e.event_type = 'wrk req'
   AND e.event_sub_type IN ('received',
                            'completed')
   AND e.incident_id = n.incident_id)
AND e.event_type = 'wrk req'
AND d.incident_status_pd='o'
GROUP BY n.incident_no,
     e.event_sub_type
ORDER BY n.incident_no

这是上述查询的当前答案

------------------------------------
incident_no event_sub_type  qty
------------------------------------
2008099999  COMPLETED   2
2008099999  RECEIVED    1
2013123456  RECEIVED    1
2014141414  COMPLETED   1
2014141414  RECEIVED    2
2016111111  RECEIVED    1

我只想要那些收到的时间超过完成时间

这就是我想要的上述查询的答案

------------------------------------
incident_no event_sub_type  qty
------------------------------------
2013123456  RECEIVED    1
2014141414  RECEIVED    2
2016111111  RECEIVED    1

1 个答案:

答案 0 :(得分:1)

我认为这是另一种情况,使用旧式连接会让人更难理解实际发生的事情 - 正如您可以看到这里的子查询在功能上与您的相同 - 但更简单(并且更简单)我的意思是更简单的阅读)没有两个EXISTS。然后使用它作为子查询来比较总数是微不足道的。

  SELECT incident_no, 'RECEIVED' as event_sub_type, R_COUNT as qty
  FROM 
  (
    SELECT n.incident_no,
           e.event_sub_type,
           SUM(CASE WHEN lower(e.event_sub_type) = 'recieved' THEN 1 ELSE 0 END) AS R_COUNT,
           SUM(CASE WHEN lower(e.event_sub_type) = 'completed' THEN 1 ELSE 0 END) AS C_COUNT
    FROM tb_event e
    JOIN tb_incident n ON e.incident_id = n.incident_id AND lower(e.event_sub_type) IN ('received', 'completed')
    JOIN vius_def d ON n.incident_id = d.incident_id
    WHERE e.event_type = 'wrk req' AND d.incident_status_pd='o'
    GROUP BY n.incident_no
  ) X
  WHERE R_COUNT > C_COUNT