簡體   English   中英

SQL Oracle 的子查詢 COUNT

[英]SQL subquery COUNT for Oracle

在我的 Oracle 數據庫中,我有兩個表T1主鍵k1T2復合主鍵k1, k2 我想 select T1中的所有列以及T2中的行數,例如T1.k1 = T2.k1

看起來很簡單,但我不知道如何使用COUNT function 來獲得這個結果,知道嗎?

我沒有你的表,所以我會嘗試使用 Scott 的示例emp和 dept 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 function 和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 function:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM