在一个表上加入两个具有最大聚合的表

时间:2013-09-05 06:13:16

标签: sql sql-server database

我有两张桌子:

材料

ID

价格

BookPrice
PriceDate
MaterialID

我想获取所有材料及其最后价格(价格行最近PriceDate)。

我正在使用SQL Server。

提前致谢!

2 个答案:

答案 0 :(得分:1)

使用outer apply

select M.ID, P.BookPrice
from Material as M
    outer apply (
        select top 1 P.BookPrice
        from Price as P
        where P.MaterialID = M.ID
        order by P.PriceDate desc
    ) as P

您也可以使用row_number(),但外部应用方法通常较慢:

with cte as (
    select
        M.ID, P.BookPrice,
        row_number() over(partition by M.ID order by P.PriceDate) as row_num
    from Material as M
        left outer join Price as P on P.MaterialID = M.ID
)
select
    c.ID, c.BookPrice
from cte as c
where c.row_num = 1

答案 1 :(得分:1)

尝试以下方法:

SELECT c.ID, d.BookPrice, d.PriceDate 
FROM Material as c
INNER JOIN
    (SELECT MaterialID, BookPrice, PriceDate 
     FROM Price as a
     WHERE PriceDate = 
          (SELECT MAX(PriceDate) 
           FROM Price as b 
           WHERE a.MaterialID = b.MaterialID
          )
    ) as d 
ON c.ID = d.MaterialID

如果需要,请参阅SQLFiddle example进一步调查。