如何在sqlite中更改月份

How to change month in sqlite

月份从 2019 年 9 月 16 日开始到 2019 年 10 月 15 日结束 如果命运是 11/10/2019,我希望月份是 9 而不是 10.. 它适用于 vb =(月(字段!Id.invdate.value)+IIF(日(字段!Id.invdate.value)<16,9,10) Mod 12+1

如何在 sqlite 中执行 SELECT DISTINCT t1.AccNo,t1.InvDate,ifnull((SELECT MIN(t1min.InvDate) FROM t1 AS t1min WHERE t1min.InvDate > t1.InvDate AND t1.AccNo = t1min.AccNo), DATE(t1.InvDate,'start of month','+1 month', '0 day')) AS NextDate,

Strftime('%m',t1.InvDate) AS 周期 '这是如果日期 16/09 期间是 9 如果日期 11/10 期间显示 10 而不是 9

对于 SQLite,您可以使用类似的东西:-

WITH 
    cte_month_start AS (SELECT 16) /* THE START DAY FOR THE MONTH */,

    /* REFORMAT THE DATE TO YYYY-MM-DD format*/
    cte_reformatted_date(rdate) AS (
        SELECT(substr(mydate,7,4)||'-'||substr(mydate,4,2)||'-'||substr(mydate,1,2)) 
        FROM mytable
        ),

    /* SUBTRACT 1 FROM THE MONTH IF THE DAY OF THE MONTH IS LESS THAN THE START DAY */
    cte_adjusted_date(adate) AS (
        SELECT  
            CASE 
                WHEN CAST(strftime('%d',rdate) AS INTEGER) < (SELECT * FROM cte_month_start) 
                THEN date(rdate,'-1 months')
                ELSE rdate
            END
        FROM cte_reformatted_date
        )
SELECT substr(adate,9,2)||'/'||substr(adate,6,2)||'/'||substr(adate,1,4) AS mydate FROM cte_adjusted_date;

这使用了 3 Common Table Expressions(临时表在查询)

  • 第一个是月份的开始日,有助于发挥灵活性的潜力

    • 即月份的开始日期可以很容易地传递,因此可以改变。
  • 第二次将日期重新格式化为 SQLites 可以轻松操作的日期 Date And Time Functions

  • 第三个利用前一个CTE输出未更改的日期(如果该月的第几天不小于该月的开始日期)或通过减去1个月调整的日期如果该月的第几天小于开始日期,则从该日期开始。

  • 您实际上不需要 CTE,它们可以嵌入,但使用它们可以使代码更容易理解。

使用 SQLite,如果日期以可识别的格式存储(根据 link),那么日期的操作会更简单。

Example/Demo

/* PREPARE TEST ENVIROMENT BY CREATING AND POPULATING TABLES */
DROP TABLE IF EXISTS mytable;
CREATE TABLE If NOT EXISTS mytable(mydate TEXT);
INSERT INTO mytable VALUES 
    ('16/09/2019'),('17/09/2019'),('18/09/2019'), /* DATES UNCHANGED */
    ('01/10/2019'),('02/10/2019'),('11/10/2019'), /* DATES THAT WILL BE ADJUSTED (month reduced)*/
    ('16/08/2019'),('11/09/2019') /* Other dates */
    ;

/* THE ACTUAL TEST */
WITH 
    cte_month_start AS (SELECT 16) /* THE START DAY FOR THE MONTH */,

    /* REFORMAT THE DATE TO YYYY-MM-DD format*/
    cte_reformatted_date(rdate) AS (
        SELECT(substr(mydate,7,4)||'-'||substr(mydate,4,2)||'-'||substr(mydate,1,2)) 
        FROM mytable
        ),

    /* SUBTRACT 1 FROM THE MONTH IF THE DAY OF THE MONTH IS LESS THAN THE START DAY */
    cte_adjusted_date(adate) AS (
        SELECT  
            CASE 
                WHEN CAST(strftime('%d',rdate) AS INTEGER) < (SELECT * FROM cte_month_start) 
                THEN date(rdate,'-1 months')
                ELSE rdate
            END
        FROM cte_reformatted_date
        )
/* RESULTS OF THE TEST */
SELECT substr(adate,9,2)||'/'||substr(adate,6,2)||'/'||substr(adate,1,4) AS mydate FROM cte_adjusted_date;
DROP TABLE IF EXISTS mytable; /* CLEAN UP TEST ENVIRONMENT */

结果:-

可以看出,突出显示的行已相应调整。