Oracle:如何连接两个结果集查询(基于同一个表)然后减去结果?

问题描述 投票:2回答:1

我的问题

我有两个查询具有相同的select和from条件但具有不同的where语句。每个查询都会计算“操作”的数量。第一个查询计算所有创建的文件,而另一个查询计算所有已删除的文件。要获取更新的文件计数,我需要加入它们,然后从创建的结果集计数中减去已删除的结果集计数。

这是我的两个问题。它们本质上是相同的,除了其中一个已创建table2.auditid = 15而另一个已删除table2.auditid = 14。

创建:

SELECT decode(table1.id,
2984, 'Category 1',
3298, 'Category 2',
2390, 'Category 3',
4039, 'Category 4',
5048, 'Category 5',
'Unknown') "Category",
COUNT (table1.id) AS "Files Created"
FROM table1
JOIN
maintable ON maintable.dataid = table1.id
JOIN 
table2 ON table2.dataid = maintable.id
JOIN
table3 ON table3.id = table2.userid
WHERE table2.auditid = 15
AND auditdate >= %1
AND table2.subtype = 0
AND table1.subtype = -18
GROUP BY table1.id

删除:

SELECT decode(table1.id,
2984, 'Category 1',
3298, 'Category 2',
2390, 'Category 3',
4039, 'Category 4',
5048, 'Category 5',
'Unknown') "Category",
COUNT (table1.id) AS "Files Created"
FROM table1
JOIN
maintable ON maintable.dataid = table1.id
JOIN 
table2 ON table2.dataid = maintable.id
JOIN
table3 ON table3.id = table2.userid
WHERE table2.auditid = 14
AND auditdate >= %1
AND table2.subtype = 0
AND table1.subtype = -18
GROUP BY table1.id

请注意,这些查询可以自行运行。


我试过的

  • 我不能使用减号语句,因为它不适用于结果集(我忘了这个并且之前已经问过这个问题)
  • 我试图将这两个查询嵌套为子查询并使用union等,但无法使其工作。
  • 我尝试过(SQL sum 2 different column by different condtion then subtraction and add)中描述的方法。这给了我错误ORA-00904 String Invalid Identifier“table1.id。

这是我改编的代码:

select decode(table1.id,
2984, 'Category 1',
3298, 'Category 2',
2390, 'Category 3',
4039, 'Category 4',
5048, 'Category 5',
'Unknown') "Category", 
(filescreated.CNT - filesdeleted.CNT) as "Final Count", 
from (
 SELECT table1.id, 
 COUNT(table1.id) as CNT
 FROM table1
 JOIN
 maintable ON maintable.dataid = table1.id
 JOIN 
 table2 ON table2.dataid = maintable.id
 JOIN
 table3 ON table3.id = table2.userid
 WHERE table2.auditid = 15
 AND auditdate >= %1
 AND table2.subtype = 0
 AND table1.subtype = -18
 GROUP BY table1.id) filescreated,
    (SELECT table1.id,
    COUNT(llattrdata.defid) as CNT
    FROM table1
    JOIN
    maintable ON maintable.dataid = table1.id
    JOIN 
    table2 ON table2.dataid = maintable.id
    JOIN
    table3 ON table3.id = table2.userid
    WHERE table2.auditid = 14
    AND auditdate >= %1
    AND table2.subtype = 0
    AND table1.subtype = -18
    GROUP BY table1.id) filesdeleted

ORDER BY table1.id

谁能提供一些见解?

sql oracle
1个回答
1
投票

在“已删除”查询块中,您仍然在"Files Created"列表中提供列名称SELECT;我认为这是一个错误,它应该是"Files Deleted",对吧?

要回答您的问题:您可能会识别table2.auditid属性“已创建”与“已删除”的文件,对吗? 15个用于创建,14个用于删除?

要在单个查询中捕获两者,最后一组where条件的那一部分应该成为

... where table2.auditid in (14, 15)  and   ...

那么你只需要改变外部select中的聚合函数 - 它需要是一个sum,并且需要一个条件求和。

count(table1.id)计算非空值。我假设id不能为null,因此它与count(*)相同 - 或者,甚至sum(1)。这将有助于当前的任务:当你想为每个sum(1)添加1但是为每个table2.auditid = 15减去1时,你需要什么而不是table2.auditid = 14

sum(decode(table2.auditid, 15, +1, 14, -1))   [as <whatever>]

祝好运!

© www.soinside.com 2019 - 2024. All rights reserved.