如何在SQLite中的季度中对日期进行分组

问题描述

我需要将日期分组为季度,四月至六月为第一季度,七月至九月为第二季度,十月至十二月为第三季度,一月至三月为第四季度

enter image description here

除了显示季度的close_dates外,我还需要添加另一列。我找不到我可以使用的任何日期函数。 任何想法。

解决方法

您可以提取月份部分并使用大小写表达式:

select
    close_date,case 
        when 0 + strftime('%m',close_date) between  1 and  3 then 'Q4'
        when 0 + strftime('%m',close_date) between  4 and  6 then 'Q1'
        when 0 + strftime('%m',close_date) between  7 and  9 then 'Q2'
        when 0 + strftime('%m',close_date) between 10 and 12 then 'Q3'
    end as quarter
from mytable

添加0可以强制将strftime()的结果转换为数字。

这也可以使用日期伪指令(也可以生成会计年度)来表达:

select 
    close_date,strftime('%Y',close_date,'-3 months') 
        || 'Q' || ((strftime('%m','-3 months') - 1) / 4) as year_quarter
from mytable
,

我会用算术而不是case表达式来做到这一点:

select floor( (strftime('%m',close_date) + 2) / 3 ) as quarter
,

日期格式为 YYYY-MM-DD,这是SQLite唯一有效的日期格式。
因此,如果要提取日期中的月份,则SQLite支持的任何date函数都将失败。
您必须使用字符串函数SUBSTR()提取月份,然后使用NULLIF()COALESCE()之类的其他函数来根据需要调整季度。
假设您的日期格式为DD/MM/YYYY

SELECT Close_Date,'Q' || COALESCE(NULLIF((SUBSTR(Close_Date,4,2) - 1) / 3,0),4) AS Quarter
FROM tablename

如果格式为MM/DD/YYYY,则将SUBSTR(Close_Date,2)更改为SUBSTR(Close_Date,1,2)或仅更改为Close_Date,因为SQLite会将日期隐式转换为数字,该数字将是数字的起始数字。日期。

请参见demo
结果:

> Close_Date | Quarter
> :--------- | :------
> 01/04/2019 | Q1     
> 01/05/2019 | Q1     
> 01/10/2019 | Q3     
> 01/09/2019 | Q2     
> 01/06/2019 | Q1     
> 01/09/2019 | Q2     
> 01/04/2019 | Q1     
> 01/07/2019 | Q2 

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...