我有一个包含一串数字的字段
"2002 2005 2001 2006 2008 2344"
我们最好假设空格是拆分,否则,它们每个是 4 个字符长。
我可以选择一个子字符串:
SELECT substr(years,1,4) FROM TABLE
但不知道如何检查每一个。我试图找到包含最接近 0 的数字的行。
我可以ORDER BY
和LIMIT 1
。
这看起来很丑,但它在一个 SQLlite 语句中选择了您需要的所有内容。如果假设日期在当前间隔内,例如 1900..2100,您也可以进行一些优化。在这种情况下,您可以先剪切 2 个选择 B,C (B: 1 union 2) (C: 9 union 0 union 1)
select years2,years from
(
select i1||i2||i3||i4 as years2 from (select '0' as i1
union all
select '1' as i1
union all
select '2' as i1
union all
select '3' as i1
union all
select '4' as i1
union all
select '5' as i1
union all
select '6' as i1
union all
select '7' as i1
union all
select '8' as i1
union all
select '9' as i1) B,
(select '0' as i2
union all
select '1' as i2
union all
select '2' as i2
union all
select '3' as i2
union all
select '4' as i2
union all
select '5' as i2
union all
select '6' as i2
union all
select '7' as i2
union all
select '8' as i2
union all
select '9' as i2) C,
(select '0' as i3
union all
select '1' as i3
union all
select '2' as i3
union all
select '3' as i3
union all
select '4' as i3
union all
select '5' as i3
union all
select '6' as i3
union all
select '7' as i3
union all
select '8' as i3
union all
select '9' as i3) D,
(select '0' as i4
union all
select '1' as i4
union all
select '2' as i4
union all
select '3' as i4
union all
select '4' as i4
union all
select '5' as i4
union all
select '6' as i4
union all
select '7' as i4
union all
select '8' as i4
union all
select '9' as i4) E
) YearsAll
left join YearsTable on (YearsTable.years like '%'||YearsAll.years2||'%')
where YearsTable.years is not null
order by years2 limit 1
您可以使用公用表表达式在年份字符串中拆分年份,然后获取最接近 0 的年份。
WITH split_years(year, years) AS (
values(0, '2001 2002 2003 2004 2005 2006'||' ')
UNION ALL SELECT
cast(substr(years, 0, instr(years, ' ')) as int),
substr(years, instr(years, ' ')+1)
FROM split WHERE length(years)
) SELECT year FROM split_years WHERE year>0 ORDER BY year LIMIT 1;
输出是:
2001