【问题标题】:as400 date queryas400日期查询
【发布时间】:2011-08-30 03:14:56
【问题描述】:

要在 as400 中查询从今天开始的最后 7 天,因为它将日期存储在 char 类型中,如何从今天开始检索结果,因为我尝试使用诸如

        where chardate >= char(days(curdate()) + 7)

但是还是不行

【问题讨论】:

    标签: information-retrieval ibm-midrange


    【解决方案1】:

    答案分为两部分。第一个涉及到这种特殊风格的 DB2 的日期数学。等效于curdate()) + 7 的DB2 表达式是current date + 7 days

    第二个涉及将日期值转换为字符值(反之亦然),以便我们可以比较它们。我们需要知道chardate 存储日期的格式,然后才能真正破解那个格式。假设它是YYYY-MM-DD 格式。然后您可以使用char(current date + 7 days, iso) 以相同格式获取未来 7 天。

    因此,根据这个假设,您的 where 语句将是

    where chardate >= char(current date + 7 days, iso)
    

    date 可以转换为几种标准日期格式:

    • ISO:YYYY-MM-DD
    • 美国:MM/DD/YYYY
    • 欧元:DD.MM.YYYY
    • JIS:YYYY-MM-DD

    如果您的chardate 格式不同,您将需要对substr 进行一些相当繁琐的工作。例如,要将YYYY-MM-DD 转换为YYYYMMDD,您需要类似

    substr(char(current date, iso), 1, 4) ||
    substr(char(current date, iso), 5, 2) ||
    substr(char(current date, iso), 7, 2)
    

    这种方法的一个主要问题是不能可靠地比较未按“年月日”顺序存储的格式。也就是说,12311969(即MMDDYYYY)将比较大于01012011,因为就数据库而言,您正在比较两个八位数字。 (这就是为什么您应该几乎总是将日期存储在实际的 date 字段或 YYYYMMDD 或类似的正确排序格式中。)

    我使用名为idate 的免费实用程序取得了巨大成功,该实用程序提供SQL 用户定义函数(UDF) 将存储在字符和数字字段中的日期转换为日期。请注意,此解决方案需要 RPG 编译器的可用性。

    【讨论】:

    • where chardate >= date(current date + 7 days, iso) 我得到错误 coloumn iso not in specified tables 并且我的日期格式是 yyyymmdd char-type 我尝试了上面的三个查询,但它没用。日期、时间或时间戳字符串中的值也无效
    • @jbs123 @dmc 在 where 语句的示例中打错了字。它应该是“其中 chardate >= char(current date + 7 days, iso)”
    • 但查询在 7 天内仍然无法正常工作
    【解决方案2】:

    从今天起的最后 7 天:

    where 
    date(substr(chardate,1,4) || '-' || 
    substr(chardate,5,2) || '-' || 
    substr(chardate,7,2)) between current date - 7 days and current date
    

    执行字符范围比较:

    where
    chardate between 
    substr(char(current date - 7 days, iso),1,4) ||
    substr(char(curernt date - 7 days, iso),6,2) ||
    substr(char(current date - 7 days, iso),9,2)
    and 
    substr(char(current date, iso),1,4) ||
    substr(char(current date, iso),6,2) ||
    substr(char(current date, iso),9,2) 
    

    【讨论】:

    • @JamesA:这可能是一个不错的选择,只要您不希望您的查询使用包含 chardate 的任何索引。
    • 但它仍然返回超过 65,000 行而不是 7 天的行
    • @jbs123:更新示例以检索最近 7 天的行。
    • 嗯,我得到了错误,因为日期、时间或时间戳字符串中的值无效是否可以将现有的字符日期列和记录转换为日期类型,我希望它是唯一的操作解决方案
    • 该错误表明您有一些记录,其中 chardate 不是 YYYYMMDD 格式或包含无效日期。您可能必须使用 CASE 语句将其过滤掉。另一种选择是按照@dmc 的建议执行字符与字符的比较,尽管您仍然会遇到无效日期的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    相关资源
    最近更新 更多