我有两个SQL查询
select count ( distinct w.processno ) AS "Number of Processes", y.userid from upmfolder f, upmperson p, w2process w, w2processcheck y where f.personid = p.personid and f.folderid = w.keynumb and w.Processno = y.processid and w.keyobject ='UPMFolder' group by 2
和另一个类似的是:
select count ( distinct w.processno ) AS "Number of Processes", y.userid from upmfolder f, upmperson p, w2process w, w2processcheck y where f.personid = p.personid and f.payrollmemberid = w.keynumb and w.keyobject = 'UPMPayrollmember' and w.Processno = y.processid group by 2
如何将两者合并为一个查询?所以计数和组仍然可以正常运行。我尝试使用union all
,但这不起作用。我需要做什么?
答案 0 :(得分:0)
您可以使用条件聚合执行此操作。对于count(distinct)
,您需要提供NULL值:
select y.userid,
count(distinct case when w.keyobject ='UPMFolder' then w.processno end) as NumFolder,
count(distinct case when w.keyobject ='UPMPayrollMember' then w.processno end) as NumPayrollMember
from upmfolder f, upmperson p, w2process w, w2processcheck y
where f.personid = p.personid and
f.folderid = w.keynumb and
w.Processno = y.processid
group by y.userid
注意:您还应该学习现代join
语法。我没有更改查询,但是连接条件应该在on
子句中,而不是在where
子句中。