【问题标题】:how to extract only month from date which is in sqlite database?如何从sqlite数据库中的日期中仅提取月份?
【发布时间】:2021-12-20 21:01:56
【问题描述】:

我想获取特定月份发生的少量数据。例如,我需要选择 7 月加入的所有员工的姓名(不考虑日期)。从数据库的日期字段中单独选择特定月份字段的查询是什么?如何比较数据库中的月份字段(以 mm/dd/yyyy 格式存储的日期)和用户给定的月份值。我正在使用 sqlite3 数据库,并且日期字段设置为文本。 提前致谢。

【问题讨论】:

  • @ditkin 这个问题没有正确答案。
  • 所有月份都以两位数存储吗?
  • 是的。我已经想出了我自己的繁琐逻辑,它运行良好,但效率不高(不包括在查询中,而是围绕解决方案)。感谢您的回复,如果您有任何其他想法,请告诉我。

标签: sqlite date


【解决方案1】:

SQLite 只有a small set of date and time functions。你可以像这样使用它们:

sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE t1 (f1 string);
INSERT INTO "t1" VALUES('03/31/1970');
COMMIT;

sqlite> select substr(f1, 7) || '-' || substr(f1, 0, 3) || '-' || substr(f1, 4, 2) from t1;
1970-03-31

sqlite> select strftime("%m", substr(f1, 7) || '-' || substr(f1, 0, 3) || '-' || substr(f1, 4, 2)) from t1;
03

【讨论】:

    【解决方案2】:

    我在 SQLITE 中使用此代码解决了这个问题。

    如果您有这样的格式:“2021-12-23 12:33:01” 然后将其转换为 strftime() 格式函数。

    ex.-> Select strftime('%d/%m/%Y',EntryDate) as Date  from table_name;
    

    然后输出进来

         "2021-12-23 12:33:01"  to "23-12-2021"
    

    然后触发此查询以从 SQLITE

    中的 MONTH NUMBER 获取 MONTH NAME
    -> using case we can fetch it.
    
    
     Select strftime('%d/%m/%Y',checkInDate) as Date, 
      case strftime('%m', checkInDate)  when '01' then 'JAN' 
      when '02' then 'FEB' when '03' then 'MAR' when '04' then 'APR' when '05' then 'MAY' when '06' then 'JUN' 
      when '07' then 'JUL' when '08' then 'AUG' when '09' then 'SEP' when '10' then 'OCT'  
      when '11' then 'NOV' when '12' then 'DEC' else '' end as Month   from AttendanceTable
    

    ☻♥ 完成保留代码。

    【讨论】:

      猜你喜欢
      • 2021-04-04
      • 2013-08-12
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 2019-03-20
      相关资源
      最近更新 更多