SQL Oracle 的子查询 COUNT

SQL subquery COUNT for Oracle

在我的 Oracle 数据库中,我有两个带有主键 k1 的表 T1 和带有复合主键 k1, k2T2。我想 select T1 中的所有列以及 T2 中的行数,例如 T1.k1 = T2.k1.

这看起来很简单,但我不知道如何使用 COUNT 函数来得到这个结果,知道吗?

我没有你的表格,所以我会尝试使用 Scott 的示例 emp 和部门 tables:

来说明它
SQL> select * from dept t1 order by t1.deptno;

    DEPTNO DNAME          LOC
---------- -------------- -------------
        10 ACCOUNTING     NEW YORK
        20 RESEARCH       DALLAS
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON

SQL> select deptno, empno, ename from emp order by deptno;

    DEPTNO      EMPNO ENAME
---------- ---------- ----------
        10       7782 CLARK     --> 3 employees in deptno 10
        10       7839 KING
        10       7934 MILLER
        20       7566 JONES     --> 5 employees in deptno 20
        20       7902 FORD
        20       7876 ADAMS
        20       7369 SMITH
        20       7788 SCOTT
        30       7521 WARD      --> 6 employees in deptno 30
        30       7844 TURNER
        30       7499 ALLEN
        30       7900 JAMES
        30       7698 BLAKE
        30       7654 MARTIN
                                --> 0 employees in deptno 40
14 rows selected.

SQL>

您可以尝试的几个选项:

相关子查询:

SQL> select t1.*,
  2         (select count(*) from emp t2 where t2.deptno = t1.deptno) cnt
  3  from dept t1
  4  order by t1.deptno;

    DEPTNO DNAME          LOC                  CNT
---------- -------------- ------------- ----------
        10 ACCOUNTING     NEW YORK               3
        20 RESEARCH       DALLAS                 5
        30 SALES          CHICAGO                6
        40 OPERATIONS     BOSTON                 0

SQL>

(外部)连接 COUNT 函数和 GROUP BY 子句:

SQL> select t1.*, count(t2.rowid) cnt
  2  from dept t1 left join emp t2 on t2.deptno = t1.deptno
  3  group by t1.deptno, t1.dname, t1.loc
  4  order by t1.deptno;

    DEPTNO DNAME          LOC                  CNT
---------- -------------- ------------- ----------
        10 ACCOUNTING     NEW YORK               3
        20 RESEARCH       DALLAS                 5
        30 SALES          CHICAGO                6
        40 OPERATIONS     BOSTON                 0

SQL>

(外部)以其解析形式与 COUNT 函数连接:

SQL> select distinct t1.*,
  2                  count(t2.rowid) over (partition by t1.deptno) cnt
  3  from dept t1 left join emp t2 on t2.deptno = t1.deptno
  4  order by t1.deptno;

    DEPTNO DNAME          LOC                  CNT
---------- -------------- ------------- ----------
        10 ACCOUNTING     NEW YORK               3
        20 RESEARCH       DALLAS                 5
        30 SALES          CHICAGO                6
        40 OPERATIONS     BOSTON                 0

SQL>