2

以下のようなBookAuthorテーブルがあります (SQL Server 2008 R2 Ent):

BookID  AuthorID
------  --------
43      676
43      76
43      354
71      89
71      76
99      71
64      50
64      39
64      354

上位 2 つの異なる BookID のすべてのレコードを取得したいと考えています。したがって、予想される出力は次のようになります。

    BookID  AuthorID
    ------  --------
    43      676
    43      76
    43      354
    71      89
    71      76

以下の最も単純なクエリを試しましたが、2 行しか返されません。

Select top 2 * from BookAuthor order by BookID ASC

それで、どうすればここに進むことができますか?どんな助けでも大歓迎です。

4

2 に答える 2

4

You can use the following to get the TOP 2 DISTINCT BookIds:

select t1.bookid, t1.authorid
from BookAuthor t1
inner join
(
  select distinct top 2 bookid
  from BookAuthor
  order by bookid
) t2
  on t1.bookid = t2.bookid

See SQL Fiddle with Demo

You stated that you want the Books with the id's 43, 71 returned because those are the top 2 book ids but data in a table is not inherently ordered. Unless you have another column that you can get the rows in that order, if you order by bookid ascending then you will return 43, 64.

于 2013-04-04T21:43:56.750 に答える
0

以下のクエリはどうですか:

Select * from BookAuthor where BookID in(
select Distinct top 2 BookID from BookAuthor order by BookID asc)

それは私にとってはうまくいっています

于 2013-04-04T21:58:48.330 に答える