在CTE中找到最大值

时间:2014-04-02 03:40:28

标签: sql sql-server-2008-r2

这是产生以下数据。到现在为止还挺好。我需要找到cte的max(list_price)。我是否应该将以下所有代码视为新的" cte2"并找到最大的?我尝试使用" max(BK.list_price)"在外部查询中,但我无法计算Group By。 (使用SQLS 2008 R2)

with cte as
(
  select BT.book_id
  from
    bkinfo.book_topics BT
  where
    BT.topic_id = 'DB'    
)
select BK.book_id, BK.list_price
from bkinfo.books BK
where BK.book_id in
(
  select cte.book_id
  from cte
)
;
go

book_id                              list_price
----------- ---------------------------------------
1105                                   59.95
1108                                   39.95
1109                                   80.00
  .
  .
  .

2 个答案:

答案 0 :(得分:2)

你真的不需要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
)

答案 1 :(得分:0)

您需要同时携带book_id及其价格,价格在主题中最高。这可能有点矫枉过正,但总的来说,您可能希望找到每个主题最Nth本书最贵的书:

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' 

Fiddle here