请看下表
书
[Id], [Name]
1 Test One
2 Test Two
3 Test Four
标签
[Id], [Name]
1 TagOne
2 TagTwo
3 TagThree
BookTag
[BookId], [TagId]
1 1
1 2
1 3
2 1
2 2
3 3
我想从上面两本书的示例中选择样本以及它们的所有相关标签,您可以按照自己喜欢的方式订购它们,这部分都没有关系。
这是我尝试过的
SELECT *
FROM (
SELECT *, 1 AS SplitOn,
(ROW_NUMBER() OVER(ORDER BY [Id] ASC)) AS RowNumber, COUNT(*) over() as TotalRows
FROM (
SELECT B.[Id], B.[Name], T.[Id] AS TagId, T.[Name] AS TagName
FROM [Book] B
LEFT OUTER JOIN [BookTag] BT ON BT.[BookId] = B.[Id]
LEFT OUTER JOIN [Tag] T ON T.[Id] = BT.[TagId]
)
)
WHERE RowNumber BETWEEN 1 AND 2
现在上述查询的问题在于,它将为每一行赋予唯一的行号,因此,我总是只获得前两行。我真正想要得到的是头2个ID的每一行。我不太清楚如何使用分区。是否可以使用Row_Number或我必须做一些完全不同的事情?
如果要按ID来查询前两本书,请使用如下子查询:
select b.*, t.name
from (select top (2) b.*
from books b
order by id
) b join
booktags bt
on bt.book_id = b.id join
tags t
on bt.tag_id = t.id;