计算当月的第一天和最后一天

时间:2017-12-08 19:59:53

标签: sqlite datetime calculator

我想计算当前日期时间当前月份的第一个日期和一周的最后日期。

例如,2017年12月1日是第一天,2017年12月2日是12月当周的最后一天。在一年的同一周,2017年11月26日是一周的第一天 2017年11月30日是上个月的最后一天。

因此,如果今天是2017年12月1日,我应该从当前日期时间而不是26-02范围获得01-02。

PS:我正在尝试在Sqlite的查询中执行此操作。我想每周对一些值进行分组。一周的日子应属于当月。因此这个要求。直到现在这是我的询问。

SELECT SUM(amount) as Y,
strftime('%d', datetime(createdOn/1000, 'unixepoch'), '-'||strftime('%w', datetime(createdOn/1000, 'unixepoch'))||' day' )
||'-'||
strftime('%d', datetime(createdOn/1000, 'unixepoch'), '+'||(6-strftime('%w', datetime(createdOn/1000, 'unixepoch')))||' day' )                 AS X
FROM my_table
GROUP BY strftime('%d', datetime(createdOn/1000, 'unixepoch'), '-'||strftime('%w', datetime(createdOn/1000, 'unixepoch'))||' day' )
||'-'||
strftime('%d', datetime(createdOn/1000, 'unixepoch'), '+'||(6-strftime('%w', datetime(createdOn/1000, 'unixepoch')))||' day' ) 

如何实现这一目标;给定当前日期时间。

1 个答案:

答案 0 :(得分:1)

Common table expressions对于保存中间结果非常有用:

WITH t1 AS (
  SELECT amount, date(createdOn / 1000, 'unixepoch', 'localtime') AS date
  FROM my_table
),
t2 AS (
  SELECT *,
         date(date, 'weekday 6') AS end_of_week,
         date(date, 'weekday 6', '-6 days') AS start_of_week
  FROM t1
),
t3 AS (
  SELECT *,
         strftime('%m', date         ) AS month,
         strftime('%m', start_of_week) AS sowk_month,
         strftime('%m', end_of_week  ) AS eowk_month,
         date(date, 'start of month') AS start_of_month,
         date(date, '+1 month', 'start of month', '-1 day') AS end_of_month
  FROM t2
),
t4 AS (
  SELECT *,
         CASE WHEN sowk_month = month THEN start_of_week
                                      ELSE start_of_month
         END AS week_in_month_start,
         CASE WHEN eowk_month = month THEN end_of_week
                                      ELSE end_of_month
         END AS week_in_month_end
  FROM t3
),
t5 AS (
  SELECT amount,
         week_in_month_start || '-' || week_in_month_end AS week_in_month
  FROM t4
)
SELECT SUM(amount) AS Y,
       week_in_month
FROM t5
GROUP BY week_in_month;