1

我有一张桌子叫作稿

BOOKID  AUTHORID BOOKNAME       GENRE   NOOFCOPIES  AMOUNT
B105    A102     Diagnosis      Journal 500         10000
B102    A102     The Essence... Fiction 110         11000
B106    A102     Clinical Sci.  Educat. 125         18750
B104    A103     Mind Games     Fiction 200         20000
B100    A102     Sublime        Fiction 100         10000
B101    A105     C Programming  Educati 125         18750
B103    A101     Scribe         Journal 500         10000
B107    A101     Clinical Chem. Educat. 125         54646
B108    A103     Clinical Chem. Educat. 125         54646  

如何获取已支付最高金额的 AuthorId?如果我写

select distinct a.AuthorId,m.amount 
from Author a,manuscripts m 
where m.amount in (select max(amount) 
                   from manuscripts m 
                   where a.AuthorId=m.AuthorId)

然后我能够得到正确的输出,但如果我添加 bookname 那么它不会正确产生..

4

2 回答 2

3

因为你没有提到你正在使用的 RDBMS,所以下面的查询几乎可以工作 RDBS,(不是全部

SELECT  a.*
FROM    tablename a
        INNER JOIN
        (
            SELECT  AuthorID, MAX(Amount) max_amount
            FROM    tableName
            GROUP   BY AuthorID
        ) b ON  a.AuthorID = b.AuthorID AND
                a.Amount = b.max_amount

为了获得更快的性能,请INDEXAuthorID, Amount

于 2013-02-08T09:53:30.450 回答
0

这将显示价格最高的每一行:

SELECT m.*
FROM amanuscripts m
WHERE m.amount = (select MAX(amount) FROM manuscripts)

这将显示每个作者的价格最高的每一行:

SELECT m.*
FROM manuscripts m
WHERE (m.authorid, m.amount) IN (select authorid, MAX(amount)
                                 FROM manuscripts
                                 GROUP BY authorid)

(鉴于上面表格的结构,无需将 Author 表与 Manuscripts 表连接)

于 2013-02-08T09:56:39.960 回答