Sql 在CTE中查找最大值

Sql 在CTE中查找最大值,sql,sql-server-2008-r2,Sql,Sql Server 2008 R2,这将产生以下数据。到现在为止,一直都还不错。我需要找到cte的最大(标价)。我是否应该把下面的所有代码看作一个新的“CTE2”并找到它的最大值?我尝试在外部查询中使用“max(BK.list\u price)”,但是我无法计算分组依据。(使用SQLS 2008 R2) 您并不需要CTE来实现这一点: select MAX(BK.list_price) from bkinfo.books BK where exists ( select BT.book_id from bkinfo

这将产生以下数据。到现在为止,一直都还不错。我需要找到cte的最大(标价)。我是否应该把下面的所有代码看作一个新的“CTE2”并找到它的最大值?我尝试在外部查询中使用“max(BK.list\u price)”,但是我无法计算分组依据。(使用SQLS 2008 R2)


您并不需要CTE来实现这一点:

select MAX(BK.list_price)
from bkinfo.books BK
where exists
(
    select BT.book_id
    from bkinfo.book_topics BT
    where BT.topic_id = 'DB'
    and BT.book_id = BK.book_id
)

您需要携带
图书id
及其价格,其中价格在主题中最高。这可能有些过分,但一般来说,您可能希望找到每个主题最贵的第n本书:

with cteBookCostsPerTopic as
(
  select 
     BT.book_id, BK.list_price, BT.topic_id,
     ROW_NUMBER() OVER (PARTITION BY BT.topic_ID ORDER BY list_price DESC) as Rnk
  from
    books BK
    INNER JOIN book_topics BT
      ON BT.book_id = BK.book_ID
)
SELECT topic_id, book_id, list_price
  FROM cteBookCostsPerTopic
  WHERE  Rnk=1-- i.e. most expensive
         and topic_id = 'DB' 

您是只需要最高价格作为返回结果,还是还需要显示与之关联的图书id?Szymon:返回与上述数据相同的数据。我需要整张桌子的最高价格。我相信这将是一个标量结果。对不起,误解了。现在检查一下。
with cteBookCostsPerTopic as
(
  select 
     BT.book_id, BK.list_price, BT.topic_id,
     ROW_NUMBER() OVER (PARTITION BY BT.topic_ID ORDER BY list_price DESC) as Rnk
  from
    books BK
    INNER JOIN book_topics BT
      ON BT.book_id = BK.book_ID
)
SELECT topic_id, book_id, list_price
  FROM cteBookCostsPerTopic
  WHERE  Rnk=1-- i.e. most expensive
         and topic_id = 'DB'