gpt4 book ai didi

sequelize.js - 如何计算列的值并按范围分组?

转载 作者:行者123 更新时间:2023-12-03 22:17:45 24 4
gpt4 key购买 nike

如果我在表中有一个年龄列,我如何检索落入 5 个范围的值的计数?

我目前有一个查询,它只获取年龄不为空或未定义的用户数。

User.findAll({
where: {
age: {
[Op.not]: null,
[Op.notIn]: ['null', 'undefined']
},
},
group: ['age', 'count'],
attributes: [
['age', 'label'],
[Sequelize.fn('count', Sequelize.col('user_id')), 'count']
],
})

电流输出: {label: 28, count: 86}
想要的结果:
ages: {
0-20: 5,
20-40: 39,
40-60:28,
60-80:11,
80-100:3
}

最佳答案

所以最后我为此使用了文字查询:

User.findAll({
where: {
age: {
[Op.not]: null,
[Op.notIn]: ['u', 'undefined', 'x', '']
}
},
attributes: [
[Sequelize.literal('COUNT (CASE WHEN age < 20 THEN age END)'), '<20'],
[Sequelize.literal('COUNT (CASE WHEN age >= 20 AND age <= 29 THEN age END)'), '20-29'],
[Sequelize.literal('COUNT (CASE WHEN age >= 30 AND age <= 39 THEN age END)'), '30-39'],
[Sequelize.literal('COUNT (CASE WHEN age >= 40 AND age <= 49 THEN age END)'), '40-49'],
[Sequelize.literal('COUNT (CASE WHEN age >= 50 THEN age END)'), '≥50'],
[Sequelize.fn('count', Sequelize.col('user_id')), 'count']
]
}),

关于sequelize.js - 如何计算列的值并按范围分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56524242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com