SQL - 获取当年每个月的最后一天 - SQLITE3

时间:2018-06-04 12:03:49

标签: sql date sqlite

我已经在SO中匆匆忙忙地发现了许多有用的查询,但不完全是我想要的,甚至他们说这是答案,但它对sqlite3根本不起作用。

所以我们走了。我想在当年每个月的最后一天返回所有数据。如下所示:(只是忽略时间,只是想把它添加到我的领域实际上看起来像)

Name | Date_Added
=================================
Bob  | 2018-01-31 05:23:06.021421
Bob  | 2018-02-28 14:16:03.076021
Bob  | 2018-03-31 13:16:03.076021
Bob  | 2018-04-30 13:16:03.076021
Bob  | 2018-05-31 13:16:03.076021
Bob  | 2018-06-04 13:16:03.076021
Mary | 2018-01-31 13:16:03.076021
Mary | 2018-02-28 13:16:03.076021
Mary | 2018-03-31 13:16:03.076021
Mary | 2018-04-30 13:16:03.076021
Mary | 2018-05-31 13:16:03.076021
Mary | 2018-06-04 13:16:03.076021

我尝试过这样的事情:

SELECT * FROM tableName WHERE date('now','start of month','-1 month','-1 day') ORDER BY "Name"

但它似乎仍然发送不仅仅是在最后一天的数据

非常感谢任何帮助或指示!

2 个答案:

答案 0 :(得分:1)

如果日期是该月的最后一天,那么如果您添加一天,则月份会有所不同:

SELECT * FROM tableName 
    WHERE 
        strftime("%m", Date_Added) != strftime("%m", Date_Added, "+1 day")
            AND 
        strftime("%Y", Date_Added) = strftime("%Y", "now")
ORDER BY "Name";

答案 1 :(得分:0)

SELECT * FROM tableName WHERE
 "Date_added" BETWEEN date('2018-12-30','start of month','-10 month','-1 day') AND date('2018-12-30','start of month','-10 month','0 day') OR 
 "Date_added" BETWEEN date('2018-12-30','start of month','-9 month','-1 day') AND date('2018-12-30','start of month','-9 month','0 day') OR 
 "Date_added" BETWEEN date('2018-12-30','start of month','-8 month','-1 day') AND date('2018-12-30','start of month','-8 month','0 day') OR 
 "Date_added" BETWEEN date('2018-12-30','start of month','-7 month','-1 day') AND date('2018-12-30','start of month','-7 month','0 day') OR 
 "Date_added" BETWEEN date('2018-12-30','start of month','-6 month','-1 day') AND date('2018-12-30','start of month','-6 month','0 day') OR 
 "Date_added" BETWEEN date('2018-12-30','start of month','-5 month','-1 day') AND date('2018-12-30','start of month','-5 month','0 day') OR 
 "Date_added" BETWEEN date('2018-12-30','start of month','-4 month','-1 day') AND date('2018-12-30','start of month','-4 month','0 day') OR 
 "Date_added" BETWEEN date('2018-12-30','start of month','-3 month','-1 day') AND date('2018-12-30','start of month','-3 month','0 day') OR 
 "Date_added" BETWEEN date('2018-12-30','start of month','-2 month','-1 day') AND date('2018-12-30','start of month','-2 month','0 day') OR 
 "Date_added" BETWEEN date('2018-12-30','start of month','-1 month','-1 day') AND date('2018-12-30','start of month','-1 month','0 day') OR 
 "Date_added" BETWEEN date('2018-12-30','start of month','0 month','-1 day') AND date('2018-12-30','start of month','0 month','0 day') 
ORDER BY "Name"

相当乏味,但正在为我工​​作!