【发布时间】:2018-11-02 07:27:54
【问题描述】:
我的问题
我有两个查询具有相同的 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
请注意,这些查询本身运行良好。
我的尝试
- 我不能使用减号语句,因为它不适用于结果集(我忘记了这一点,之前曾问过这个问题)
- 我尝试将这两个查询嵌套为子查询并使用联合等,但无法正常工作。
- 我已经尝试过 (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
谁能提供一些见解?
【问题讨论】: