SQL组合不同表的两个查询

时间:2015-03-20 15:45:35

标签: sql oracle

我有以下查询连接表:

select scholarship_id as scholId,
       count(scholarship_id) as incompleteCount
from applicant_scholarship
group by scholarship_id

select scholarship_id as scholId,
       count(scholarship_id) as completeCount
from applicant_comp_schol
group by scholarship_id

我希望将两个查询合并,并为我提供一个包含scholId,incompleteCount和completeCount的表。有人可以帮忙吗?

使用以下内容进行解决:

  SELECT scholId,
     SUM (completeCount) AS completeCount,
     SUM (incompleteCount) AS incompleteCount,
     SUM (completeCount) + SUM (incompleteCount) AS totalCount
  FROM (  SELECT scholarship_id AS scholId,
               COUNT (scholarship_id) AS incompleteCount,
               NULL AS completeCount
          FROM applicant_scholarship
      GROUP BY scholarship_id
      UNION
        SELECT scholarship_id AS scholId, NULL, COUNT (scholarship_id)
          FROM applicant_comp_schol
      GROUP BY scholarship_id)
  GROUP BY scholId

3 个答案:

答案 0 :(得分:1)

select scholarship_id as scholId, 
count(scholarship_id) as incompleteCount 
null as completeCount
from applicant_scholarship group by scholarship_id
group by scholarship_id
Union
select scholarship_id as scholId, 
null,
count(scholarship_id) 
from applicant_comp_schol
group by scholarship_id

答案 1 :(得分:1)

你可能还有一个表,其中包含完整的记录列表,这些记录将是你的基础(确保你抓住"零")。假设你这样做,你可以将你的两个查询保留为你离开加入的子查询:

select
    s.scholarship_id
    ,nvl(inc.num_records, 0) incompleteCount
    ,nvl(cpl.num_records, 0) completeCount
from
    scholarships s
left join (
    select
        scholarship_id
        ,count(scholarship_id) num_records
    from applicant_scholarship 
    group by scholarship_id
) inc on s.scholarship_id = inc.scholarship_id
left join (
    select
        scholarship_id
        ,count(scholarship_id) num_records
    from applicant_comp_schol
    group by scholarship_id
) cpl on s.scholarship_id = cpl.scholarship_id

如果你没有那些真正的奖学金和#34;包含所有内容的表,然后您可以构建另一个子查询,将这两个表联合在一起以获取组合的唯一scholarship_id值,然后将其用作基表。

答案 2 :(得分:0)

假设您在每个表中都有唯一标识符,则可以使用完全外部联接来完成此操作:

SELECT   COALESCE (aps.scholarship_id, acs.scholarship_id) AS scholid,
         COUNT (DISTINCT aps.applicant_scholarship_id) AS incompletecount,
         COUNT (DISTINCT acs.applicant_comp_schol_id) AS incompletecount
FROM     applicant_scholarship aps
         FULL OUTER JOIN applicant_comp_schol acs
            ON aps.scholarship_id = acs.scholarship_id
GROUP BY scholarship_id

显然,我假设applicant_scholarship_idapplicant_comp_schol_id存在。 Scholarship_ID将无法在这些地方使用,因为它会导致错误的计数。