Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SQLite中按季度分组日期_Sql_String_Sqlite_Datetime_Sql Date Functions - Fatal编程技术网

如何在SQLite中按季度分组日期

如何在SQLite中按季度分组日期,sql,string,sqlite,datetime,sql-date-functions,Sql,String,Sqlite,Datetime,Sql Date Functions,我需要将日期分组为季度,4月至6月为第一季度,7月至9月为第二季度,10月至12月为第三季度,1月至3月为第四季度 除了显示季度的结束日期之外,我还需要添加另一列。我找不到任何可以使用的日期函数。 对此有何想法。您可以提取月份部分并使用case表达式: select close_date, case when 0 + strftime('%m', close_date) between 1 and 3 then 'Q4' when 0 +

我需要将日期分组为季度,4月至6月为第一季度,7月至9月为第二季度,10月至12月为第三季度,1月至3月为第四季度

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

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

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
select floor( (strftime('%m', close_date) + 2) / 3 ) as quarter
添加
0
可以强制将
strftime()
的结果转换为数字

这也可以使用date Artimetics表示(它也可以生成会计年度):


我会用算术而不是
case
表达式:

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
select floor( (strftime('%m', close_date) + 2) / 3 ) as quarter

日期格式为而不是
YYYY-MM-DD
,这是SQLite唯一有效的日期格式。
因此,如果要提取日期的月份,SQLite支持的任何日期函数都将失败。
您必须使用字符串函数提取月份,然后使用其他函数(如和)根据需要调整季度。
假设日期的格式为
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,4,2)
更改为
SUBSTR(Close_Date,1,2)
或只是
Close_Date
,因为SQLite会隐式地将日期转换为一个数字,该数字将是日期的起始数字。

请参阅。
结果:


看看这是否有帮助:这并没有显示如何将日期划分为季度:(我运行了第一个查询,结果在col下为get Nonequarter@user14140366:这似乎适用于…您以何种格式存储日期?我必须是
YYYY-MM-DD
,sqlite才能将其识别为日期。在jupyter中运行数据类型时,我将对象类型作为类型