Gra*_*tzy 3 sql t-sql sql-server sql-server-2005
此查询的目的是恢复销售产品的产品及其价格,价格应该从最接近但不等于传递日期的日期开始,基本上是最近可用的价格.每天都没有价格记录.在where子句中使用聚合select语句有点不对劲.有一个更好的方法吗?也许在加入标准?
select
p.ProductName,
pp.Price,
pp.Date,
from product p
inner join productprice pp on p.productid = pp.productid
where
pp.evaluationdate = (select max(Date) from productprice
where productid = p.productid
and date < @DateIn)
and p.producttype = 'OnSale'
Run Code Online (Sandbox Code Playgroud)
实际的查询有点复杂,但这基本上是问题所在.感谢您的输入.
编辑 将返回多个产品
编辑 我正在试验@Remus Rusanu和@ km的建议(虽然@Remus Rusanu删除了他的)三个,包括我原来的,在性能方面似乎差不多.我试图决定一个人是否以其他一些无形的方式提供优惠,即维护,自我记录等,因为这将由其他人维持.再次感谢.
试试这个:
;WITH CurrentPrice AS
(
SELECT productid,max(Date) AS Date
FROM productprice
WHERE date < @DateIn
GROUP BY productid
)
select
p.ProductName,
pp.Price,
pp.Date,
from product p
inner join CurrentPrice pa on p.productid = pa.productid
inner join productprice pp on pa.productid = pp.productid AND pa.Date=pp.Date
where p.producttype = 'OnSale'
Run Code Online (Sandbox Code Playgroud)
编辑基于OP的评论:
我认为上面的CTE查询将与@Remus Rusanu的派生表版本具有相同的查询计划
但是,如果productprice表很大,您可能希望通过过滤" OnSale" 来减少它,如下所示:
;WITH CurrentPrice AS
(
select
p.productid,
MAX(pp.Date) AS Date
from product p
inner join productprice pp on pa.productid = pp.productid
where p.producttype = 'OnSale' AND pp.date < @DateIn
GROUP BY productid
)
select
p.ProductName,
pp.Price,
pp.Date,
from CurrentPrice pa
inner join product p on pa.productid = p.productid
inner join productprice pp on pa.productid = pp.productid AND pa.Date=pp.Date
where p.producttype = 'OnSale'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13657 次 |
| 最近记录: |