SQL查询 - 需要从不同的表中获取信息

时间:2012-04-13 20:27:30

标签: sql join count max

我正在尝试编写一个查询来获取一份报告,该报告显示哪本图书已被借出。我有一个查询,以获得实际借出的书,但我需要能够显示该书的标题,这是在另一张表中。

SELECT * FROM LOAN;

LOANID     BOOKID     CUSTID OUTDATE   INDATE    DUEDATE

SELECT * FROM BOOK;

AUTHORID     BOOKID   BKISBN   BKSTATUS   BKTITLE  BKSERIES  BKTYPE   BKNUMBER

以下查询是我到目前为止所获得的书籍。:

SELECT Q1.* FROM
(SELECT BOOKID, COUNT(*)
    AS BOOK_COUNT
  FROM LOAN
  GROUP BY LOAN.BOOKID) Q1,
(SELECT MAX(Q2.BOOK_COUNT)
    AS HIGH_COUNT
  FROM (SELECT BOOKID, COUNT(*)
    AS BOOK_COUNT
  FROM LOAN
  GROUP BY LOAN.BOOKID) Q2) Q3
WHERE Q1.BOOK_COUNT = Q3.HIGH_COUNT;

结果:

    BOOKID BOOK_COUNT
---------- ----------
       387          3

现在我需要书表中的BkTitle。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

尝试

select b.bookid, b.BKTITLE , count(l.loanid) as cnt_loan
from book b
inner join loan l on l.bookid = b.bookid
WHERE ROWNUM < 2
group by b.bookid
order by cnt_loan desc