You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Knex+SQLite3项目中如何在查询中仅获取月份?

按月份分组统计销售额(Knex + SQLite3)

要实现按月份分组统计,需要利用SQLite的strftime函数提取日期中的年月信息,同时在查询的select和groupBy中统一使用这个格式化后的字段,修正后的代码如下:

router.get("/data/graph", async (req, res) => {
    try {
        const totalPerMonth = await dbKnex("books")
            // 提取年月并命名为month,格式为YYYY-MM(如2024-05)
            .select(dbKnex.raw("strftime('%Y-%m', sell_date) as month"))
            .sum({ total: "price" })
            // 按格式化后的月份分组
            .groupBy("month");
        res.status(200).json(totalPerMonth);
    } catch(error) {
        res.status(400).json({msg: error.message});
    }
})

关键修改说明:

  • 日期格式化:使用SQLite内置的strftime('%Y-%m', sell_date)函数,将完整的sell_date转换为年-月格式的字符串,通过as month给这个计算字段起别名,方便后续分组和返回结果使用。
  • 分组依据:将groupBy("sell_date")改为groupBy("month"),确保按月份而非具体日期分组统计。

可选格式调整:

如果需要更易读的月份格式(如"2024年5月"),可以修改strftime的格式参数:

.select(dbKnex.raw("strftime('%Y年%m月', sell_date) as month"))

注意事项:

  • SQLite的strftime函数遵循C语言的日期格式规范,常用格式符包括%Y(4位年份)、%m(2位月份)、%d(2位日期)等。
  • 若sum返回的total出现字符串类型问题,可以显式转换类型:
    .sum({ total: dbKnex.raw("cast(price as real)") })
    

内容的提问来源于stack exchange,提问作者Pedro Guilherme Rosa Lutz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 18:52:21