How to define a date interval in a compatible way?
I am trying to construct the SQL query, that should be executed as is both on HSQL (v2.2.4) and MySQL (v5.1.36) server (if it can run also on DB2 v9, that would be wonderful bonus!)
The query is:
select count(*) from document where current_date - cast(indexing_date as date) <= ?
(here current_date
is a standard HSQL/MySQL function and indexing_date
is a column with type datetime
, parameter ?
is substituted by integer 20
which is the num开发者_如何学运维ber of days).
The problem is that MySQL returns the difference between dates as between numbers while HSQL returns the difference in days (which is logical when you subtract date from date).
Also HSQL supports this syntax (but MySQL does not):
select count(*) from document where cast(indexing_date as date) between current_date - 20 day and current_date
while MySQL does not. I am aware about DATEDIFF()
in MySQL, but as I said the solution should be inter-operable.
HSQLDB also supports this:
select count(*) from document where current_date - cast(indexing_date as date) <= cast(? as interval day)
and
select count(*) from document where cast(indexing_date as date) between current_date - '20' day and current_date
or
select count(*) from document where indexing_date >= current_date - interval '20' day
Also, from version 2.2.6, HSQLDB supports DATEDIFF(datevaluea, datevalueb)
, which returns the number of days between the two dates, as well as DAYS(datevalue)
, which returns the day number since the epoch.
db2:
SELECT COUNT(*)
FROM document
WHERE DATE(indexing_date) BETWEEN DATE(DAYS(CURRENT DATE) - 20) AND CURRENT DATE
精彩评论