首页 > 解决方案 > 按时间戳分组 sqlite3

问题描述

我有一个具有如下时间戳的列。我想按月份分组。我正在使用下面的查询。但在大型数据集中,它有时会给出错误的结果。我想说的是在那个时间戳中使用 group by (每月)的任何其他方式吗?

 SELECT count(distinct a) from abc GROUP BY (select strftime('%m', timestamp) as valMonth) where col1 like '%a%'

timestamp              a      co1
2020-01-23 17:22:57    12     a    
2020-01-23 17:26:59    12     a
2020-02-23 17:26:59    13     b
2020-02-23 17:26:59    13     b
2020-03-23 17:26:59    14     a
2020-03-23 17:26:59    14     a

标签: sqlite

解决方案


如果您使用:

strftime('%m', timestamp)

那么你只按月分组,所以结果将是例如所有年份的所有 12 月的 1 个组。
您应该按年份和月份分组:

strftime('%Y-%m', timestamp)

因此,将您的查询更改为:

SELECT strftime('%Y-%m', timestamp) AS YearMonth,
       ............... 
FROM abc 
GROUP BY YearMonth

推荐阅读