简体   繁体   English

如何在SQL中获得日期之间的差异

[英]How to get difference between dates in SQL

I have seen other answers but my question is different because I want to get the difference between two dates and use it in the where clause but its asking me to enter days to get difference. 我看到了其他答案,但是我的问题有所不同,因为我想获得两个日期之间的差值,并在where子句中使用它,但是它要求我输入天数以得到差值。 The dates are coming from my database. 日期来自我的数据库。

Select datediff(D, cid, ced) as theDateDiff
from customers 

Select datediff(D, cid, ced) as theDateDiff
from customers where theDateDiff>=5

假设cidcedcustomers表中的字段,则不妨尝试以下操作:

select * from customers c where datediff("d", c.cid, c.ced) >= 5

Consider following two issues involving your MS Access SQL: 考虑以下涉及您的MS Access SQL的两个问题:

  1. In most cases with some exceptions, you cannot use an alias of a calculated column in other parts of same level query. 在大多数情况下,除了某些例外情况,您不能在同一级别查询的其他部分中使用计算列的别名。 You can however use such an alias if residing in another query or subquery. 但是,如果驻留在另一个查询或子查询中,则可以使用这样的别名。

     SELECT * FROM (SELECT *, DateDiff("d", cid, ced) AS theDateDiff FROM customers) sub where theDateDiff >= 5 
  2. The DateDiff function in MS Access differs from the DateDiff of SQL Server where the latter appears to be the version you use with unquoted D as first argument. MS Access中的DateDiff函数与SQL Server的DateDiff不同,后者的SQLDATEDiff似乎是您使用的版本,其中以无引号D开头。 Remember no two dialects in the relational database world are exactly alike even if under same parent company. 请记住,即使在同一母公司下,关系数据库世界中也没有两个方言是完全一样的。

    Therefore, replace DateDiff(D, cid, ced) with DateDiff("d", cid, ced) . 因此,将DateDiff(D, cid, ced)替换为DateDiff("d", cid, ced)

    To cite another example other than Microsoft, Oracle (company) now manages MySQL which is a very different RDBMS with much different dialect than flagship database: Oracle. 举一个Microsoft以外的例子,Oracle(公司)现在管理MySQL,这是一个与旗舰数据库有很大不同的方言的RDBMS:Oracle。

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

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