SQL Server 2008 GROUP BY
I am stuck and I am trying to find a solution, so please help!
I have 3 tables:
Books (id, title, ...)
Authors (id, name, surname, ...)
book_authors (bookID, authorID, whatisdoing)
Now I want to retrieve all books depending on the title (user search) and all the other info (author name, surname). But, I want the bo开发者_如何学编程ok titles to be unique with only the first occurrence of the book_authors.whatisdoing
to be shown.
In MS Access I achieved that with first
function, but now first
does not work and with min
I didn't get the results I want.
Any help would be appreciate.
The query in Access was:
SELECT
First(book_authos.whatisdoing) AS FirstOfidiothta_ID,
First(authors.name) AS onoma,
First(authors.surname) AS eponymo,
books.ID, books.title, books.photoLink
FROM (books
INNER JOIN book_authors ON books.ID = book_authors.book_ID)
INNER JOIN authors ON book_authors.author_ID = authors.ID
GROUP BY
books.ID, books.titlos, books.photoLink, books.active
HAVING
(((books.titlos) Like '%" & textString & "%') AND
((books.active)=True) AND ((First(authors.active))=True))
ORDER BY
First(book_authos.whatisdoing), books.title
EDIT: Changed based on OP comments.
EDIT 2: Revised to correct flaws.
You might give this a try.
SELECT aba.name, aba.surname, aba.whatisdoing,
b.ID, b.title, b.photoLink
FROM Books b
JOIN
(
SELECT ba.bookID, ba.whatisdoing, a.name, a.surname,
ROW_NUMBER() OVER (PARTITION BY ba.bookID ORDER BY ba.whatisdoing) AS sequence
FROM book_authors ba
JOIN Authors a ON ba.authorID = a.id
WHERE a.active = 1
) AS aba ON b.id = aba.bookID
WHERE b.title LIKE '%' + @textString + '%'
AND b.active = 1
AND aba.sequence = 1
The ROW_NUMBER function assigns a row number to the row based on the groups defined in the PARTITION BY clause and the order defined by the ORDER BY clause.
@textString is a SQL Server variable. I'm not sure how you would assign this in your situation.
The boolean data type is BIT in SQL Server and the values are 0 for false and 1 from true.
精彩评论