我想找到本周和select dayofweek(datetime), avg(value) from Temperatures where week(datetime) = week(now()) group by dayofweek(datetime);
分组的平均值,所以我写了这个sql,sql运行良好,但我如何才能通过sequelize达到同样的目的。
Temperatures
这是我的
| field | type |
|----------|-------------|
| uuid | char(36) |
| value | float |
| datetime | datetime |
表:
where
我已经阅读了续集的文档,但似乎没有明确解释如何在where: {
[Sequelize.Op.eq]: [
sequelize.fn('week', Temperature.sequelize.fn('now')),
sequelize.fn('week', Temperature.sequelize.col('datetime')),
]
},
句后使用函数,条件是函数而不是字段。
我已经尝试了,但它不起作用
import photo from "../img/reed.jpg";
const styles = {
background: `url(${photo})`
};
感谢您的帮助!
答案 0 :(得分:0)
您可以使用sequelize.fn
,例如:
[sequelize.fn('dayofweek', sequelize.col('datetime')), 'datetime']
答案 1 :(得分:0)
最后,我发现以下方法效果很好
return Temperature.findAll({
attributes: [
[Temperature.sequelize.fn('dayofweek', Temperature.sequelize.col('datetime')), 'dayofweek'],
[Temperature.sequelize.fn('AVG', Temperature.sequelize.col('value')), 'value'],
],
where: sequelize.where(sequelize.fn('week', Temperature.sequelize.fn('now')), sequelize.fn('week', Temperature.sequelize.col('datetime'))),
group: sequelize.fn('dayofweek', Temperature.sequelize.col('datetime')),
});
如果我需要更多的条件过滤器,只需添加一个[Op.and]运算符
return Temperature.findAll({
attributes: [
[Temperature.sequelize.fn('dayofweek', Temperature.sequelize.col('datetime')), 'dayofweek'],
[Temperature.sequelize.fn('AVG', Temperature.sequelize.col('value')), 'value'],
],
where: {
[Sequelize.Op.and]: [
sequelize.where(sequelize.fn('week', Temperature.sequelize.fn('now')), sequelize.fn('week', Temperature.sequelize.col('datetime'))),
]
},
group: sequelize.fn('dayofweek', Temperature.sequelize.col('datetime')),
});
这里是sql生成的
SELECT dayofweek(`datetime`) AS `dayofweek`, AVG(`value`) AS `value` FROM `Temperatures` AS `Temperature` WHERE (week(now())=week(`datetime`)) GROUP BY dayofweek(`datetime`);