我有一个 SQLite 数据库表,其中包含日期列。日期列的值跨越 2023 年和 2024 年。该表包含 2023 年 11 月和 2024 年 5 月的条目。 当我执行以下sql时
SELECT trans.date as 'transdate' FROM 'Transaction' trans WHERE transdate >= '01-01-2024' AND transdate <= '05-21-2024'
我得到了 5 月的值,正如我所期望的那样。当我使用前一年执行 SQL 时
SELECT trans.date as 'transdate' FROM 'Transaction' trans WHERE transdate >= '11-01-2023' AND transdate <= '05-21-2024'
我什么也没得到。它不会识别前一年。
我理解“日期”是一个关键字。但这似乎并不重要,因为当我仅使用今年的值时查询有效。 (2024)
我知道“日期”是一个关键字。
date 不是关键字,而是一个内置函数,它将从已知/识别的日期/时间格式的值返回 yyyy-mm-dd。
您的问题是由于所比较的值的重要性所致。例如11(月份)大于 05(即 1 大于 0),年份是最不重要的。
也许考虑以下示例/演示:-
DROP TABLE IF EXISTS ex01;
CREATE TABLE IF NOT EXISTS ex01 (
date /* not a keyword so valid as a column name*/ whatever_type_does_not_really_matter,
time /* again time is not a keyword */ again_whatever_type_does_not_really_matter,
other date /* as above SQLite types are only indicative so can be anything
IMPORTANTLY SQLite does not have date/time/timestamp specific column types, rather it has
inbuilt date and time functions that will produce results IF the value conforms to recognised datetime formats
*/
);
INSERT INTO ex01 VALUES
/* row should be selected as 2023-11-01 is in range */
('11-01-2023','2023-11-01' /* equivalent date where parts are in order of signifcance */,'not a date but that does not matter!!!!')
/* row should be in range */
,('11-02-2023','2023-11-02','not a date but that does not matter!!!!')
/* row not in range i.e. 2023-05.02 is less than 2023-11-01 */
,('05-02-2023','2023-05-02','not a date but that does not matter!!!!')
/* row should be in range */
,('05-01-2024','2024-05-01','not a date but that does not matter!!!!')
/* row out of range i.e. 2024-06-01 is greater than 2024-05-01 */
,('06-01-2024','2024-06-01','not a date but that does not matter!!!!')
;
SELECT * FROM ex01 ORDER BY date;
SELECT * FROM ex01 ORDER BY time;
/*
example of converting the mm-dd-yyyy format to yyyy-mm-dd (and therefore order of significance)
*/
SELECT * FROM ex01 WHERE
substr(date,7,4)||'-'||substr(date,1,3)||substr(date,4,2) >= '2023-11-01'
AND substr(date,7,4)||'-'||substr(date,1,3)||substr(date,4,2) <= '2024-05-01'
;
/*
Show what the 2 parts of the comparison result in
*/
SELECT *,
date >= '11-01-2023' AS isGrtOrEqAsPerQuestion,
date <= '05-01-2024' AS isLessOrEqAsPerQuestion,
substr(date,7,4)||'-'||substr(date,1,3)||substr(date,4,2) >= '2023-11-01' AS isGreaterOrEq,
substr(date,7,4)||'-'||substr(date,1,3)||substr(date,4,2) <= '2024-05-01' AS isLessThanOrEq,
date(date) AS dateFunctionAppliedToDateColumn,
date(time) AS dateFuntionApplidaToTimeColumn
FROM ex01
ORDER BY time
;
/* Cleanup test environment */
DROP TABLE IF EXISTS ex01;
该演示创建了一个包含 3 列的表格:-
whatever_type_does_not_really_matter
date
,请注意,这再次具有 NUMERIC 的亲和力,尽管它听起来像是一种类型(由其他数据库支持)其次添加一些行。
第三个是根据第一个date列查询所有行ORDER的结果,所以排序的意义是MM-DD-YYYY:-
第四个是结果,但按 time 列排序,其重要性为 YYYY-MM-DD(可以像日期一样排序):-
第五是范围的提取,首先是问题中的标准,但提取了date列的部分,以根据重要性对它们重新排序:-
第六是显示上述一些结果的摘录:-