【问题标题】:How to filter date with where on SQLite with '2021-07-31 13:53:26' format?如何在 SQLite 上以“2021-07-31 13:53:26”格式过滤日期?
【发布时间】:2021-08-25 08:46:32
【问题描述】:

我想只取“2021-07-31 13:53:26”中的年份和月份,并根据计数值对它们进行分组。

我尝试了 date、datetime、strftime 函数。

日期和日期时间结果为空。 strftime 结果,但我无法将我得到的年份和月份与我想要的计数分组,再次导致 null

这是数据的预览。

预期结果示例类似于“2021-07”,计算今年和月份出现的次数

这是我尝试使用 strftime 的语法:

select strftime('%Y%m', started_at) year_month, count(year_month) from bike_trip
group by year_month

谢谢

【问题讨论】:

  • 到目前为止你尝试过什么?你被困在哪里了?
  • 我试过日期、日期时间、strftime。日期和日期时间结果为空。 strftime 结果,但我无法将它们与我想要的 coutn 分组@NicoHaase
  • 请编辑您的问题以包含所有说明。您究竟尝试了什么?
  • @NicoHaase 已编辑
  • @forpas 这行得通,谢谢

标签: sql sqlite


【解决方案1】:

Sqlite 没有日期数据类型,因此您需要进行字符串比较来实现这一点。

with d as (
  select '2021-07-31 13:53:26'  as d, 'A' val  union all
  select '2021-08-30 13:53:26'  as d, 'B' val
)
select substr(d,1,4) as yyyy, substr(d,6,2) as mm, count(*) 
from d
group by substr(d,1,4), substr(d,6,2)

在您的查询中:

select substr(started_at,1,4) as yyyy, substr(started_at,6,2) as mm, count(*) 
from bike_trip
group by substr(started_at,1,4), substr(started_at,6,2)

【讨论】:

    【解决方案2】:

    使用 CTE 获得答案。

    with
    -- uncomment to test
    /*bike_trip(started_at) as (
        values
        ('2021-07-31 13:53:26'),
        ('2021-07-17 19:06:01'),
        ('2021-08-30 13:53:26')
    ),*/
    bike_months(year_month) as (
        select strftime('%Y-%m', started_at) year_month from bike_trip
    )
    select year_month, count(year_month) count_year_month from bike_months
    group by year_month;
    

    输出:

    year_month|count_year_month
    2021-07|2
    2021-08|1
    

    【讨论】:

    猜你喜欢
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2021-10-03
    • 1970-01-01
    相关资源
    最近更新 更多