我有一个包含以下字段的表:
AuthorID
BookTitle
PageNo
Key
Value
主键是由以下组成的复合键:AuthorID, BookTitle, PageNo, Key
我需要一个查询,显示所有BookTitles for AuthorID =“ABC”,以及键“Field1”的值从第一页开始,以及“Field2”的值从最后一页开始。
我有以下查询:
SELECT BookTitle
, a.FieldFromFirstPage
, [Value] As FieldFromLastPage
, b.LastPage
FROM Table1
INNER JOIN (SELECT BookTitle, [Value] As FieldFromFirstPage
FROM Table1
WHERE [Key]='Field1'
and PageNo=1
and AuthorID='ABC') As a ON BookTitle=a.BookTitle
INNER JOIN (SELECT BookTitle, MAX(PageNo) As LastPage
FROM Table1
WHERE AuthorID='ABC'
GROUP BY BookTitle
HAVING MAX(PageNo)> 0) As b ON BookTitle=b.BookTitle AND PageNo=b.LastPage
WHERE [Key]='Field2' and AuthorID='ABC'
这适合我,但我想知道是否有更好的方法使用条件聚合或其他方法来做到这一点?
答案 0 :(得分:0)
首先,我要问桌子的设计。应该有一个带有AuthorID的表格(为什么这个字母数字?希望你不要将作者的名字保存为ID!)和一个以BookID作为参考的表格页面。 但是 - 从来没有 - 这应该工作:
编辑:替换了第一次尝试,因为它不起作用。希望这次更好,但没有数据就很难测试......
--Fetch only books of the given AuthorID
WITH bookCTE AS
(
SELECT DISTINCT AuthorID,BookTitle
FROM Table1
WHERE AuthorID='ABC'
)
SELECT bookCTE.BookTitle
,(
SELECT TOP 1 t.Field1
FROM Table1 AS t
WHERE t.AuthorID=bookCTE.AuthorID
AND t.BookTitle=bookCTE.BookTitle
AND t.PageNo=1
) AS FieldFromFirstPage
,LastPageNumber.*
,(
SELECT TOP 1 t.Field2
FROM Table1 AS t
WHERE t.AuthorID=bookCTE.AuthorID
AND t.BookTitle=bookCTE.BookTitle
AND t.PageNo=LastPageNumber.LastPage
) AS FieldFromLastPage
FROM bookCTE
--find the max page number
CROSS APPLY(SELECT MAX(x.PageNo) FROM Table1 AS x WHERE x.AuthorID=bookCTE.AuthorID AND x.BookTitle=bookCTE.BookTitle) AS LastPageNumber(LastPage)