繁体   English   中英

使用附加group by插入子查询的解决方案

[英]Solution to insert sub-query with additional group by

我正在尝试在Oracle SQL Developer中合并两个正在运行的SQL查询,但似乎无法让sub的Group By发挥得很好。 我希望/期望看到每行的单独总计,但我得到所有行的总计。

我尝试将第二个查询添加为子查询。

查询1:

SELECT SOURCE,   
sum(case when status = 'C1' then 1 else 0 end) as "C1",
sum(case when status = 'C2' then 1 else 0 end) as "C2",
sum(case when status = 'C3' then 1 else 0 end) as "C3",
sum(case when status = 'C4' then 1 else 0 end) as "C4",
sum(case when status = 'C5' then 1 else 0 end) as "C5" 
FROM TABLE.req 
GROUP BY SOURCE 
ORDER BY SOURCE;

查询2将添加到上面:

SELECT SOURCE, COUNT(REQ.SOURCE) AS "Done in 7 Days"
FROM TABLE.req REQ
    JOIN TABLE.audit AUD ON REQ.ROW_ID = AUD.RECORD_ID
WHERE (AUD.LAST_UPD - REQ.CREATED) <= 7 
    AND REQ.STATUS = 'Complete'
    GROUP BY SOURCE;

尝试子查询:

SELECT SOURCE,   
sum(case when status = 'C1' then 1 else 0 end) as "C1",
sum(case when status = 'C2' then 1 else 0 end) as "C2",
sum(case when status = 'C3' then 1 else 0 end) as "C3",
sum(case when status = 'C4' then 1 else 0 end) as "C4",
sum(case when status = 'C5' then 1 else 0 end) as "C5"    
(SELECT SOURCE, COUNT(REQ.SOURCE) 
FROM TABLE.req REQ
    JOIN TABLE.audit AUD ON REQ.ROW_ID = AUD.RECORD_ID
WHERE (AUD.LAST_UPD - REQ.CREATED) <= 7 
    AND REQ.STATUS = 'Complete'
GROUP BY SOURCE) AS "Done in 7"
FROM TABLE.req 
GROUP BY SOURCE 
ORDER BY SOURCE;


Query 1 returns:

A   0   0   0   0   0
B   0   0   3026    26  2461
C   0   0   0   0   0
D   3   39  2   1   19
E   0   0   61156   0   79430

Query 2 returns:

A   2906
B   10
C   28
D   7
E       0

ACTUAL:Sub-Query返回附加列但是它被总计

A   0   0   0   0   0           2951
B   0   0   3026    26  2461    2951
C   0   0   0   0   0           2951
D   3   39  2   1   19          2951
E   0   0   61156   0   79430   2951

EXPECTED:子查询返回其总计的附加列BUT

A   0   0   0   0   0           2906
B   0   0   3026    26  2461    10
C   0   0   0   0   0           28
D   3   39  2   1   19          7
E   0   0   61156   0   79430   0

您似乎想要一个相关的子查询:

SELECT SOURCE,   
       sum(case when status = 'C1' then 1 else 0 end) as "C1",
       sum(case when status = 'C2' then 1 else 0 end) as "C2",
       sum(case when status = 'C3' then 1 else 0 end) as "C3",
       sum(case when status = 'C4' then 1 else 0 end) as "C4",
       sum(case when status = 'C5' then 1 else 0 end) as "C5",  
       (SELECT COUNT(*) 
        FROM TABLE.req REQ r2 JOIN
             TABLE.audit a
             ON r2.ROW_ID = a.RECORD_ID
       WHERE r2.SOURCE = r.SOURCE AND
             (a.LAST_UPD - r2.CREATED) <= 7 AND
             r2.STATUS = 'Complete'
      )
FROM TABLE.req  r
GROUP BY SOURCE 
ORDER BY SOURCE;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM