简体   繁体   English

查询返回日期范围中的行但仅返回列的最大值

[英]Query to return rows in date range but return only max value of column

What I want to do is select the price from a table where the date given is between the start and finish date in a table. 我想要做的是从表中选择价格,其中给定的日期在表格中的开始日期和结束日期之间。

SELECT price 
FROM table 
WHERE 'dategiven' BETWEEN startdate AND enddate

This is easy enough with a datetime filter. 使用日期时间过滤器很容易。 Problem is I have multiple records in the time window provided, I have a version column as well. 问题是我在提供的时间窗口中有多个记录,我也有一个版本列。

I have below an example of my table: 我有一个我的表的例子:

在此输入图像描述

I want my query output to be as below where my dategiven is 2013-08-25 我希望我的查询输出如下所示我的dategiven2013-08-25 在此输入图像描述

Milk has 3 records, 2 of them are valid for dategiven (2013-08-25). 牛奶有3条记录,其中2条对dategiven有效(2013-08-25)。 I then want to return the result with the highest version? 然后我想以最高版本返回结果?

something like: 就像是:

SELECT
    price 
FROM table 
WHERE 'dategiven' BETWEEN startdate AND enddate AND max(version)

Using the row_number() function to rank the rows 使用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

May not be the most efficient way but: 可能不是最有效的方式,但:

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 
    )

You can also try this 你也可以试试这个

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

Hope it helps. 希望能帮助到你。

my computer installed is not sqlservert but mysql. 我安装的电脑不是sqlservert而是mysql。 I do not know it is complex. 我不知道它很复杂。

  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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM