我想要做的是从表格中选择价格,其中给定的日期在表格中的开始日期和结束日期之间。
SELECT price
FROM table
WHERE 'dategiven' BETWEEN startdate AND enddate
使用日期时间过滤器很容易。问题是我在提供的时间窗口中有多个记录,我也有一个版本列。
我的表格下面有一个例子:
我希望我的查询输出如下所示dategiven
为2013-08-25
Milk有3条记录,其中2条对dategiven
有效(2013-08-25)。然后我想以最高版本返回结果?
类似的东西:
SELECT
price
FROM table
WHERE 'dategiven' BETWEEN startdate AND enddate AND max(version)
答案 0 :(得分:2)
使用row_number()
函数对行进行排名
select product, price, version
from
(
select
*,
row_number() over (partition by product order by version desc) rn
from yourtable
where @dategiven between startdate and enddate
) v
where rn = 1
答案 1 :(得分:1)
可能不是最有效的方式,但是:
select price
from table
where
'dategiven' between startdate and enddate
and version =
(
select max(version) from table t2 where t2.product = table.product
and 'dategiven' between startdate and enddate
)
答案 2 :(得分:1)
你也可以尝试这个
select t.product, t.price, version
from table t
inner join
(select product, max(version) maxVerion from table where
'dategiven' between startdate and enddate group by product) temp
on temp.product = t.product and t.version = temp.maxVerion
希望它有所帮助。
答案 3 :(得分:0)
我安装的电脑不是sqlservert而是mysql。我不知道它很复杂。
select t.product, t.price, v.version
(
select temp.product, max(temp.version) as version
from
(
select product, price, startDate, endDate, version
from Table
where 'dategiven' between startDate and endDate
) as temp
group by temp.product
) as v
inner join Table as t
on v.version = t.version