简体   繁体   English

日期列为“ YYYYMMDD”字符串-如何选择过去30天以上的所有行?

[英]Date column as “YYYYMMDD” string - how to select all rows >= 30 days in the past?

I have a table which contains a VALID_TO column as VARCHAR2. 我有一个表,其中包含一个VALID_TO列作为VARCHAR2。 This column has date strings in format "YYYYMMDD", eg "20160624". 此列中的日期字符串格式为“ YYYYMMDD”,例如“ 20160624”。

ID     ARTICLE_NUMBER   STORE_ID   COUNTRY   VALID_TO
----------------------------------------------------------------
100    111              22         AT        20160624
...

What I need is a SELECT that gives me all rows having a VALID_TO date that is 30 days old or older. 我需要的是SELECT,它使我所有具有VALID_TO日期为30天或更早的行。 Any idea how to achieve it? 知道如何实现吗?

Seems pretty straightforward; 似乎很简单; find the date 30 days ago, convert it to the same format, and use that for your filter: 查找30天前的日期,将其转换为相同的格式,然后将其用于您的过滤器:

where valid_to <= to_char(sysdate - 30, 'YYYYMMDD')

Simple demo using a CTE to generate 40 dates: 使用CTE生成40个日期的简单演示:

with t42 (valid_to) as (
  select to_char(trunc(sysdate) - level, 'YYYYMMDD') from dual connect by level <= 40
)
select valid_to
from t42
where valid_to <= to_char(sysdate - 30, 'YYYYMMDD');

VALID_TO
--------
20160525
20160524
20160523
20160522
20160521
20160520
20160519
20160518
20160517
20160516
20160515

 11 rows selected 

While your stored format makes this kind of search do-able, it's still better to store dates as actual dates rather than as string. 虽然您的存储格式使这种搜索成为可能,但是将日期存储为实际日期而不是字符串仍然更好。 There's little stopping you putting an invalid value in there, eg 20161357... 几乎没有阻止您在其中输入无效值的情况,例如20161357 ...

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

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