【问题标题】:SQL return a value at a specific date in timeSQL 在特定时间返回一个值
【发布时间】:2014-02-06 01:27:15
【问题描述】:

我正在尝试查找某个日期的值。

我的数据看起来像

Date        Value
2013-11-02   5
2013-10-10   8
2013-09-14   6
2013-08-15   4

如何确定 2013-09-30 的值是多少?

显然答案是 6,但我无法弄清楚 SQL 代码。

谢谢

【问题讨论】:

  • 你用的是什么数据库?
  • 答案是否为 6 并不是很明显,因为 2013-09-30 不会出现在您的数据中。我现在假设日期表示状态更改,并且状态(值)保持在日期之间的最新值。如果是这种情况,您应该在问题中明确说明,以便每个人都在同一页面上。

标签: sql date select


【解决方案1】:

您可以使用order by 并限制行数来做到这一点。在 SQL Server 语法(以及 Sybase 和 Access)中:

select top 1 t.*
from table t
where date <= '2013-09-30'
order by date desc;

在 MySQL(和 Postgres)中:

select t.*
from table t
where date <= '2013-09-30'
order by date desc
limit 1;

在甲骨文中:

select t.*
from (select t.*
      from table t
      where date <= '2013-09-30'
      order by date desc
    ) t
where rownum = 1

编辑:

而且,一种 SQL 标准方式(应该适用于任何数据库):

select t.*
from table t
where date = (select max(date)
              from table t2
              where date <= '2013-09-30'
             );

【讨论】:

  • 抱歉没有更清楚,这是我的第一篇文章。非常感谢您的帮助,您为我提供了几个运行选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多