-1

我有两张桌子:

材料

ID

价格

BookPrice
PriceDate
MaterialID

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

我正在使用 SQL Server。

提前致谢!

4

2 回答 2

1

使用外部申请

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
于 2013-09-05T06:15:54.050 回答
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 示例以进一步调查。

于 2013-09-05T07:22:31.640 回答