【问题标题】:order by not formatted date sqlite按未格式化的日期排序 sqlite
【发布时间】:2013-02-20 11:09:33
【问题描述】:

我将日期作为字符串存储在数据库中,格式为 DD-MM-YYYY。

当我尝试在日期列上使用 orderby 进行选择查询时。我没有得到预期的结果。

结果示例: 28/02/2013 27/02/2013 2013 年 1 月 3 日

我的sql查询:

SELECT * FROM data ORDER BY strftime('%s', date_column)

谢谢。

【问题讨论】:

    标签: sql sqlite date format


    【解决方案1】:

    这个查询对我有用过滤日期

    SELECT inst.*,
           Substr(columnname, 4, 2)  AS newdate,
           Substr(columnname, 0, 3)  AS newday,
           Substr(columnname, 12, 5) AS newtime
    FROM   table_name AS inst
    WHERE  child_id = id
    ORDER  BY newdate DESC, newday DESC, newtime DESC  
    

    【讨论】:

      【解决方案2】:

      问题是您将日期存储为 DD-MM-YYYY 字符串,这不仅会阻止日期作为字符串的自然排序,还会使用SQLite's date and time functions 解析它们。点击链接并向下滚动到“时间字符串”部分。

      SQLite 期望日期/时间字符串按自然顺序,从最高有效位到最低有效位,即 YYYY-MM-DD。您可以使用字符串操作将 DD-MM-YYYY 字符串转换为该格式。例如:

      select 
        substr(reversed_date, 7,4) || '-' || 
        substr(reversed_date, 4, 2)|| '-' ||
        substr(reversed_date, 1, 2) as proper_date
        from (
          select '12-03-2000' as reversed_date
        )
      ;
      

      您可以将日期列转换为这种格式(如@peterm 建议的那样),或者只使用proper_date 的值进行排序。您不需要为此使用 strftime,但与日期相关的函数将使用这些值。

      【讨论】:

        【解决方案3】:

        恕我直言,您需要更改存储日期的格式

        DD-MM-YYYY
        

        YYYY-MM-DD
        

        来自文档

        时间字符串 时间字符串可以是以下任何一种格式:
        YYYY-MM-DD
        YYYY-MM-DD HH:MM
        YYYY-MM-DD HH:MM:SS
        YYYY-MM-DD HH:MM:SS.SSS
        YYYY-MM-DDTHH:MM
        YYYY-MM-DDTHH:MM:SS
        YYYY-MM-DDTHH:MM:SS.SSS
        ...

        那么您的原始查询和这个查询将按预期工作

        SELECT * FROM Table1 ORDER BY date(date_column);
        SELECT * FROM Table1 ORDER BY strftime('%s', date_column);
        

        输出:

        | date_column |
        ---------------
        |  2013-02-27 |
        |  2013-02-28 |
        |  2013-03-01 |
        

        sqlfiddle

        【讨论】:

          【解决方案4】:

          尝试:

          SELECT * FROM data ORDER BY to_date(date_column)
          

          这可能会解决您的问题,因为它用于字符串比较而不是日期比较,所以

          01/03/2013 看起来小于 28/02/2013 或 27/02/2013

          因此输出是:

          2013 年 1 月 3 日,2013 年 2 月 27 日,2013 年 2 月 28 日

          【讨论】:

          • sqlite3.OperationalError: no such function: to_date
          【解决方案5】:

          根据documentation,以下应该可以工作

          SELECT * 
          FROM data 
          ORDER BY strftime('%Y-%m-%d', date_column)
          

          【讨论】:

          • 这不起作用。自己试试select strftime('%Y-%m-%d', '12-03-2000');
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-14
          • 1970-01-01
          • 2011-09-22
          • 1970-01-01
          • 2015-01-27
          相关资源
          最近更新 更多