postgresql - 子查询,用于查找特定实例后的随机实例。不作为主查询的一部分

时间:2017-01-16 12:22:14

标签: sql postgresql

为了澄清审核等,这是我之前发表的帖子的后续内容:

postgresql - Subquery to look for random instance following a specific instance

这个问题已经解决但是我现在需要将该答案作为更大查询的一部分包含在内,并且由于难以使其工作而需要提出另一个问题。

之前的查询使我能够在单个数据列表中提取绿线(如下图所示):

https://postimg.org/image/va7n814s9/

我现在需要在处理多个指定列表时循环此子查询,直到我的主查询完成了一些特定的计数。遗憾的是,在尝试实现此目的时,主查询仅执行此子查询一次而不是循环遍历所有列表。我试图用许多不同的方式对它进行编码,包括CTE和派生表样式,但无论我如何构造它,结果都是一样的。这让我相信我可能需要对子查询进行稍微不同的编码,以便主查询知道继续重复子查询条件。

为了清楚起见,这是我所拥有的最新代码的示例,因此您可以准确地看到我出错的地方(编辑后包含代码并删除代码链接,我在这里发布的道歉相对较新):

SELECT table_1.agent
      ,COUNT(DISTINCT CASE WHEN table2.queue=1 AND table2.status=0 THEN table2.id ELSE NULL END)AS count_1
      ,COUNT(DISTINCT CASE WHEN table2.queue=2 AND table2.status=0 THEN table2.id ELSE NULL END)AS count_2
      ,COUNT(DISTINCT CASE WHEN table2.queue=3 AND table2.status=0 THEN table2.id ELSE NULL END)AS count_3
      ,COUNT(DISTINCT CASE WHEN table2.queue=4 AND table2.status=0 THEN table2.id ELSE NULL END)AS count_4
FROM historic_table table_1 JOIN current_table table_2 ON table_1.reviewid=table2.id
                            JOIN (SELECT table_1a.*
                                    FROM historic table_1a
                                   WHERE table_1a.id >(SELECT MAX(table_1b.id) 
                                                         FROM historic table_1b
                                                        WHERE table_1b.queue=42)
                                ORDER BY table_1a.id FETCH FIRST 1 ROW ONLY) next_instance ON table_1.id=next_instance.id
WHERE table_1.currenttimestamp>=(current_date-7)
GROUP BY table_1.agent

非常感谢您的帮助,非常感谢!

1 个答案:

答案 0 :(得分:0)

好的,经过大量的试验和错误后,我设法写下面的代码给我想要的结果集:

WITH alpha AS 
(SELECT table1a.urid, (SELECT MIN(table1b.classifier) FROM historic_table table1b WHERE table1b.urid=table1a.urid) AS min_agent
   FROM historic_table table1a 
  WHERE table1a.queue=42
    AND table1a.tstamp>=(current_date-7))
,stats AS
 (SELECT a.min_agent AS name
        ,COUNT(DISTINCT CASE WHEN table2.queue=1 AND table2.status=0 THEN table2.id ELSE NULL END)AS count_1
        ,COUNT(DISTINCT CASE WHEN table2.queue=2 AND table2.status=0 THEN table2.id ELSE NULL END)AS count_2
        ,COUNT(DISTINCT CASE WHEN table2.queue=3 AND table2.status=0 THEN table2.id ELSE NULL END)AS count_3
        ,COUNT(DISTINCT CASE WHEN table2.queue=4 AND table2.status=0 THEN table2.id ELSE NULL END)AS count_4
    FROM current_table table2 JOIN alpha a ON table2.id=a.urid
GROUP BY a.min_agent)
   SELECT s.*
         ,s.count_1+s.count_2+s.count_3+s.count_4 AS total_count 
     FROM stats s 
 GROUP BY s.name
         ,s.count_1
         ,s.count_2
         ,s.count_3
         ,s.count_4 
  HAVING (s.count_1+s.count_2+s.count_3+s.count_4)>0 
ORDER BY total_count DESC