我有一个名为'Date'的列,这些日期格式为m / d / yyyy,当我查询“从table_nm选择日期'2015年1月20日'和'2015年1月9日之间的日期'时我得到错误的结果。
"1/2/2015"
"1/5/2015"
"1/6/2015"
"1/7/2015"
"1/8/2015"
"1/9/2015"
"1/20/2015"
"1/21/2015"
"1/22/2015"
"1/23/2015"
"1/26/2015"
"1/27/2015"
"1/28/2015"
"1/29/2015"
"1/30/2015"
答案 0 :(得分:0)
您的问题是日期不是SQLite接受的格式。
有效格式可在SQL As Understood By SQLite - Date And Time Functions - Time Strings
找到您的日期使用的格式特别笨拙,因为月份和日期可以是1或2个字符。最可能合适的格式是YYYY-MM-DD,例如: 2015年1月30日
您可以使用以下内容作为解决方案的基础: -
SELECT *,
CASE
WHEN CAST(month AS INTEGER) < 10 AND CAST(dayinmonth AS INTEGER) < 10 THEN year||'-0'||month||'-0'||dayinmonth
WHEN CAST(month AS INTEGER) < 10 AND CAST(dayinmonth AS INTEGER) >= 10 THEN year||'-0'||month||'-'||dayinmonth
WHEN CAST(month AS INTEGER) >= 10 AND CAST(dayinmonth AS INTEGER) < 10 THEN year||'-'||month||'-0'||dayinmonth
WHEN CAST(month AS INTEGER) >= 10 AND CAST(dayinmonth AS INTEGER) >= 10 THEN year||'-'||month||'-'||dayinmonth
END AS newdate
FROM (
SELECT
*,
substr(date,length(date)-3) AS year,
substr(date,1,instr(date,'/')-1) AS month,
substr(
substr(date, instr(date,'/')+1),
1,
instr(substr(date, instr(date,'/')+1),'/') -1
)
AS dayinmonth
FROM mytable002
)
WHERE newdate BETWEEN '2015-01-02' AND '2015-01-09'
mytable002用于测试的表格如下: -
结果输出为: -
谢谢,我已经使用python将这些数据导入sqlite, 转换每一行并不容易。
以上可能是非常简单转换的基础。您可以添加一列,然后根据上述内容将重新格式化的日期存储到该列中。
e.g。 : -
ALTER TABLE mytable002 ADD COLUMN newcolumn TEXT;
WITH updatedata (newdate,olddate) AS (
SELECT
CASE
WHEN CAST(month AS INTEGER) < 10 AND CAST(dayinmonth AS INTEGER) < 10 THEN year||'-0'||month||'-0'||dayinmonth
WHEN CAST(month AS INTEGER) < 10 AND CAST(dayinmonth AS INTEGER) >= 10 THEN year||'-0'||month||'-'||dayinmonth
WHEN CAST(month AS INTEGER) >= 10 AND CAST(dayinmonth AS INTEGER) < 10 THEN year||'-'||month||'-0'||dayinmonth
WHEN CAST(month AS INTEGER) >= 10 AND CAST(dayinmonth AS INTEGER) >= 10 THEN year||'-'||month||'-'||dayinmonth
END AS newdate,
date AS olddate
FROM (
SELECT
*,
substr(date,length(date)-3) AS year,
substr(date,1,instr(date,'/')-1) AS month,
substr(
substr(date, instr(date,'/')+1),
1,
instr(substr(date, instr(date,'/')+1),'/') -1
)
AS dayinmonth
FROM mytable002
)
)
UPDATE mytable002
SET newcolumn = (
SELECT newdate
FROM updatedata
WHERE mytable002.date = olddate
)
;