Oracle SQL 加入并计数

Oracle SQL with Join and count

我想加入两个 tables,A 和 B,具有计数功能。

Table A 有以下内容:

SQL> select a.book_id, count(a.book_id)
   from
   a 
   group by a.book_id ; 

BOOK_ID COUNT(A.BOOK_ID)
--------- ----------------
    1                2
    2                2
    3                2
    4                2
    5                2
    6                3

和table B 有以下内容:

 SQL> select b.book_id, count(b.book_id)
from
b 
group by b.book_id ; 

 BOOK_ID COUNT(B.BOOK_ID)
--------- ----------------
     6                2

所以我想查询得到以下结果:

 BOOK_ID COUNT(A.BOOK_ID)    COUNT(B.BOOK_ID)
--------- ----------------   ----------------
    1                2                   0
    2                2                   0
    3                2                   0
    4                2                   0
    5                2                   0
    6                3                   2

我试过这个:

  SQL> select b.book_id, count(b.book_id),a.book_id, count(a.book_id)
  from
  b , a 
  where
  b.book_id(+) = a.book_id
 group by b.book_id, a.book_id ;

但结果是这样的:

   BOOK_ID COUNT(B.BOOK_ID)   BOOK_ID COUNT(A.BOOK_ID)
 --------- ---------------- --------- ----------------
                     0         1                2
                     0         2                2
                     0         3                2
                     0         4                2
                     0         5                2
    6                6         6                6

也许是这样的:

select  a.book_id as id_a,  
        (select count(1) from a a2 where a2.book_id = a.book_id) as count_a,
        b.book_id as id_b,
        (select count(1) from b b2 where b2.book_id = a.book_id) as count_b
from a
left join b on b.book_id  = a.book_id
group by a.book_id;

另一种方法:

WITH total_list AS (
    SELECT a.Book_id, 'a' AS a_cnt, NULL AS b_cnt FROM a
    UNION ALL
    SELECT b.Book_id, NULL, 'b')
SELECT Book_id, COUNT(a_cnt) AS a_total, COUNT(b_cnt) AS b_total
GROUP BY Book_id
ORDER BY Book_id

它的作用是使用子查询将您的两本书 table 联合在一起,并在其上附加一个标志以表示它属于 table a 还是 table b.从那里,我刚刚从子查询中选择。