简体   繁体   English

在SQL查询中同时使用count和union

[英]Using count and union together in SQL query

I have two SQL queries 我有两个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

and another similar one is : 另一个类似的是:

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

How would I combine the two into just one query? 如何将两者合并为一个查询? So the count and group would still function correctly. 因此,计数和组仍将正常运行。 I tried with union all , however this didn't work. 我试着用union all ,但这没用。 What do I need to do? 我需要做什么?

You can do this with conditional aggregation. 您可以使用条件聚合来做到这一点。 For a count(distinct) you need to supply a NULL value: 对于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

Note: You should also learn modern join syntax. 注意:您还应该学习现代join语法。 I haven't changed the query, but the join conditions should really be in an on clause rather than in the where clause. 我没有更改查询,但是连接条件实际上应该在on子句中,而不是在where子句中。

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

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