两个日期之间的天数 - ANSI SQL

发布于 2024-08-12 15:49:26 字数 57 浏览 11 评论 0原文

我需要一种方法来确定 SQL 中两个日期之间的天数。

答案必须是 ANSI SQL。

I need a way to determine the number of days between two dates in SQL.

Answer must be in ANSI SQL.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

如歌彻婉言 2024-08-19 15:49:26

ANSI SQL-92 将 DATE - DATE 定义为返回 INTERVAL 类型。您应该能够使用与使用 EXTRACT 函数 (4.5.3) 从 DATE 中提取标量相同的方法从 INTERVALS 中提取标量。

<提取表达式>运行于
日期时间或间隔并返回
代表的精确数值
日期时间的一个组成部分的值
或间隔。

然而,这在大多数数据库中实现得很差。您可能无法使用特定于数据库的东西。 DATEDIFF 在不同平台上的实现都非常好。

这是“真正”的做法。

SELECT EXTRACT(DAY FROM DATE '2009-01-01' - DATE '2009-05-05') FROM DUAL;

祝你好运!

ANSI SQL-92 defines DATE - DATE as returning an INTERVAL type. You are supposed to be able to extract scalars from INTERVALS using the same method as extracting them from DATEs using – appropriately enough – the EXTRACT function (4.5.3).

<extract expression> operates on
a datetime or interval and returns an
exact numeric value representing the
value of one component of the datetime
or interval.

However, this is very poorly implemented in most databases. You're probably stuck using something database-specific. DATEDIFF is pretty well implemented across different platforms.

Here's the "real" way of doing it.

SELECT EXTRACT(DAY FROM DATE '2009-01-01' - DATE '2009-05-05') FROM DUAL;

Good luck!

山田美奈子 2024-08-19 15:49:26

我不记得使用不支持 DATE1-DATE2 和 SQL 92 似乎同意。

I can't remember using a RDBMS that didn't support DATE1-DATE2 and SQL 92 seems to agree.

暮色兮凉城 2024-08-19 15:49:26

我相信 SQL-92 标准支持使用“-”运算符减去两个日期。

I believe the SQL-92 standard supports subtracting two dates with the '-' operator.

不必你懂 2024-08-19 15:49:26

SQL 92 支持以下语法:

t.date_1 - t.date_2

EXTRACT 函数也是 ANSI 的,但 SQL Server 不支持它。示例:

ABS(EXTRACT(DAY FROM t.date_1) - EXTRACT(DAY FROM t.date_2)

将计算包装在绝对值函数中可确保结果为正值,即使较小的日期是第一个日期。

支持 EXTRACT:

  • Oracle 9i+
  • MySQL
  • Postgres

SQL 92 supports the following syntax:

t.date_1 - t.date_2

The EXTRACT function is also ANSI, but it isn't supported on SQL Server. Example:

ABS(EXTRACT(DAY FROM t.date_1) - EXTRACT(DAY FROM t.date_2)

Wrapping the calculation in an absolute value function ensures the value will come out as positive, even if a smaller date is the first date.

EXTRACT is supported on:

  • Oracle 9i+
  • MySQL
  • Postgres
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文