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
相关产品推荐
相关产品推荐

