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

How to group dates in Quarters in SQLite

我需要将我的日期分组为季度,4 月至 6 月为 Q1,7 月至 9 月为 Q2,10 月至 12 月为 Q3,1 月至 3 月为 Q4

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

您可以提取月份部分并使用 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

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

这也可以使用日期算法来表示(它也可以让您生成会计年度):

select 
    close_date,
    strftime('%Y', close_date, '-3 months') 
        || 'Q' || ((strftime('%m', close_date, '-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 支持的任何日期函数都会失败。
您必须使用字符串函数 SUBSTR() to extract the month and then other functions like NULLIF() and 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, 4, 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