选择两个表之间的连接查询

时间:2014-12-08 13:41:53

标签: sql oracle plsql

我必须以年度格式获得结果,但以下查询返回意外输出:

    SELECT EXTRACT (YEAR FROM Tab_1.DATE_STMP), COUNT (Tab_1.DATE_STMP), 

    EXTRACT (YEAR FROM Tab_2.DATE_STMP), COUNT (Tab_2.DATE_STMP) FROM  

    EMP_1 Tab_1 FULL OUTER JOIN EMP_2@LINK Tab_2  

    ON EXTRACT(YEAR FROM Tab_1.DATE_STMP)= EXTRACT(YEAR FROM Tab_2.DATE_STMP)  

    GROUP BY EXTRACT (YEAR FROM Tab_1.DATE_STMP),

    EXTRACT (YEAR FROM Tab_2.DATE_STMP);

预期输出:

2014    40  2014    20

实际输出:

2014    800 2014    800

我的长plsql解决方案是迭代DATE值并分别查询Count:

--PL/SQL
OPEN cur FOR 'SELECT DATE_STMP FROM EMP_1@LINK1 UNION SELECT DATE_STMP FROM EMP_2@LINK2'
FETCH cur INTO v_datVar;
...
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM EMP_1 WHERE EXTRACT (YEAR FROM DATE_STMP)='||v_datVar INTO v_Total2;
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM EMP_2 WHERE EXTRACT (YEAR FROM DATE_STMP)='||v_datVar INTO v_Total2;
...
--PRINT VALUES HERE

QUES。

是否有单个选择查询来获取此输出? (使用不同类型的连接或连接条件?)

3 个答案:

答案 0 :(得分:2)

您在DATE_STMP上的全外连接记录。因此,您将获得匹配和不匹配(即,其他表中的日期不匹配)。您的结果显示您甚至没有匹配,但只有不匹配。但是,似乎你对多少日期匹配并不感兴趣。此外,我敢说,你似乎甚至对多年的匹配感兴趣。您只想在两个表中计算每年的记录数。这与匹配记录和连接无关。

所以:首先获得计数。然后加入结果,以便每年获得一条记录:

select coalesce(t1.the_year,t2.the_year), t1.the_count, t2.the_count
from
(
  select extract (year from date_stmp) the_year, count(*) as the_count 
  from emp_1
  group by extract (year from date_stmp)
) t1
full outer join
(
  select extract (year from date_stmp) the_year, count(*) as the_count 
  from emp_2@link on
  group by extract (year from date_stmp)
) t2 on t2.the_year = t1.the_year;
编辑:我看到您更改了请求的查询并立即加入。如上所述,我认为你对计算匹配和不匹配并不感兴趣,所以我的答案保持不变。

答案 1 :(得分:2)

另一种方法是使用union all聚合:

SELECT y1, cnt1, y2, cnt2
FROM ((SELECT EXTRACT(YEAR FROM Tab_1.DATE_STMP) as y1, COUNT(*) as cnt1, NULL as y2, NULL as cnt2
       FROM EMP_1 Tab_1
       GROUP BY EXTRACT(YEAR FROM Tab_1.DATE_STMP)
       EMP_2@LINK Tab_2  
      ) UNION ALL
      (SELECT NULL, NULL, EXTRACT(YEAR FROM Tab_2.DATE_STMP) as y2, COUNT(*) as cnt2
       FROM EMP_1 Tab_2
       GROUP BY EXTRACT(YEAR FROM Tab_2.DATE_STMP)
      )
     )  
GROUP BY COALESCE(y1, y2)

答案 2 :(得分:1)

我认为最好将每个表分组在单独的select

SELECT TAB_1.YEAR1, TAB_1.COUNT1, TAB_2.YEAR2, TAB_2.COUNT2

FROM 
(SELECT EXTRACT (YEAR FROM DATE_STMP) AS YEAR1, COUNT(DATE_STMP) AS COUNT1
FROM EMP_1
GROUP BY EXTRACT (YEAR FROM DATE_STMP)) AS TAB_1

FULL OUTER JOIN

(SELECT EXTRACT (YEAR FROM DATE_STMP) AS YEAR2, COUNT(DATE_STMP) AS COUNT2
FROM EMP_2
GROUP BY EXTRACT (YEAR FROM DATE_STMP)) AS TAB_2

ON TAB_1.YEAR1=TAB_2.YEAR2;