如何使用UNION运算符计数

时间:2016-06-06 10:30:06

标签: oracle

我试图通过使用UNION运算符来获取总计数,但它会给出错误的计数。

select count(*) as companyRatings from (
select count(*) hrs from (
select distinct hrs from companyA
)
union           
select count(*) financehrs from (
select distinct finance_hrs from companyB
)
union           
select count(*) hrids from (
select regexp_substr(hr_id,'[^/]+',1,3) hrid from companyZ
)
union           
select count(*) cities from (
select regexp_substr(city,'[^/]+',1,3) city from companyY
)
);

个人查询工作正常但总计数不匹配。

个人结果:12 19 3 6 目前总人数:31

实际总数:40。 所以有没有UNION运算符的替代解决方案?

2 个答案:

答案 0 :(得分:1)

要添加您使用+的值。 UNION是添加数据集。

select
  (select count(distinct hrs) from companyA)
  +
  (select count(distinct finance_hrs) from companyB)
  +
  (select count(regexp_substr(hr_id,'[^/]+',1,3)) from companyZ)
  +
  (select count(regexp_substr(city,'[^/]+',1,3)) from companyY)
  as total
from dual;

但我同意juergen d;你不应该在每个公司都有单独的表格。

答案 1 :(得分:0)

编辑。使用Sum

更新了查询
select sum(cnt) as companyRatings from 
(
    select count(*) as cnt from (select distinct hrs from companyA)
    union all          
    select count(*) as cnt from (select distinct finance_hrs from companyB)
    union all        
    select count(*) as cnt from (select regexp_substr(hr_id,'[^/]+',1,3) hrid from companyZ)
    union all       
    select count(*) as cnt from (select regexp_substr(city,'[^/]+',1,3) city from companyY)
)

上一个回答:

试试这个

SELECT (
        SELECT count(*) hrs
        FROM (
            SELECT DISTINCT hrs
            FROM companyA
            )
        ) 
        + 
        (
        SELECT count(*) financehrs
        FROM (
            SELECT DISTINCT finance_hrs
            FROM companyB
            )
        ) 
        +
        (
        SELECT count(*) hrids
        FROM (
            SELECT regexp_substr(hr_id, '[^/]+', 1, 3) hrid
            FROM companyZ
            )
        )
        + 
        (
        SELECT count(*) cities
        FROM (
            SELECT regexp_substr(city, '[^/]+', 1, 3) city
            FROM companyY
            )
        ) 
AS total_count
FROM dual