1

对于甲骨文,

我有 2 张桌子;第一个是 Store,另一个是 Book,它们通过 store ID (PK FK) 连接。我想列出书籍数量最多的商店的名称。但是,结果显示每个商店都有订单,但我只想要最高的。

    SELECT STORE.STORE_NAME
    FROM STORE, BOOK
    WHERE STORE.STORE_ID=BOOK.BOOK_STOREID
    GROUP BY STORE.STORE_NAME
    ORDER BY COUNT(BOOK.BOOK_STOREID) DESC;

结果是

商店:D E F B A C

它应该只有“D”。我应该怎么办?谢谢你。

4

2 回答 2

2

尝试

SELECT STORE_NAME
FROM
(SELECT STORE.STORE_NAME
    FROM STORE, BOOK
    WHERE STORE.STORE_ID=BOOK.BOOK_STOREID
    GROUP BY STORE.STORE_NAME
    ORDER BY COUNT(BOOK.BOOK_STOREID) DESC)
WHERE rownum = 1

这是一个 sqlfiddle 演示

顺便说一句,您也可以使用 row_number() 函数

select STORE_NAME
from
(SELECT STORE.STORE_NAME, 
       row_number() over( order by COUNT(BOOK.BOOK_STOREID)desc) rn
    FROM STORE join BOOK on STORE.STORE_ID=BOOK.BOOK_STOREID
group by STORE.STORE_NAME)
where rn = 1;

更新如果您想查看拥有最大图书数量的所有商店,您可以使用 rank 而不是 row_number:

select STORE_NAME
from
(SELECT STORE.STORE_NAME, 
       rank() over( order by COUNT(BOOK.BOOK_STOREID)desc) rn
    FROM STORE join BOOK on STORE.STORE_ID=BOOK.BOOK_STOREID
group by STORE.STORE_NAME)
where rn = 1;
于 2013-05-19T13:34:47.383 回答
1

只是为了好玩,这里有另一种表述:

with store_counts as (
  select store_name,
         count(*) books
    from store join book on store_id=book_storeid
group by store_name)
select *
from   store_counts
where  books = (
         select max(books)
         from store_counts)
于 2013-05-20T11:43:42.007 回答