我的问题
我有两个查询,它们具有相同的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
请注意,这些查询可以独立运行。
我尝试过的事情
这是我改编的代码:
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
任何人都可以提供一些见识吗?
答案 0 :(得分: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>]
祝你好运!