【问题标题】:Knex calculate avg in each monthKnex 计算每个月的平均值
【发布时间】:2022-01-22 17:56:39
【问题描述】:

我有一个用时间类型定义的列和一个用日期类型定义的列。

knex.schema.createTable('receipt', function(table) {
  ...
  table.double('money');
  table.timestamp('createdAt');
  ...
});

它在 2 个月内存储数据。

[
   {
    "money": 18.80,
    "createdAt": "2021-12-01T22:20:00.000Z",
   },
   {
    "money": 38.80,
    "createdAt": "2021-11-01T22:20:00.000Z",
   },
]

当使用 SQL 查询和计算平均货币时

SELECT createdMonth, avg(money) FROM 
(
    SELECT MONTH(createdAt) as `createdMonth`, money FROM receipt
) subTable
group by createdMonth

如何在 Knexjs 中做到这一点。非常感谢。

【问题讨论】:

    标签: knex.js


    【解决方案1】:

    创建一个视图(而不是加入表,我用来创建视图)

    async function createRoleStaffView() {
        let fields = [
            `money`,
            knex.raw(`MONTH(createdAt) as ${DISTINCT_MONTH}`),
              `createdAt`
        ];
    
        var viewDefinition = knex.select(fields).from("receipt");
        return knex.schema.raw('CREATE OR REPLACE VIEW ?? AS (\n' + viewDefinition + '\n)', ["receipt"]).then(() => {
            Logger.info("ResourceAccess", "[DONE]createOrReplaceView: receipt");
        });
    }
    

    最后,查询它。

    knex("receipt").select(DISTINCT_MONTH).avg({ avgMoney: "money" }).groupBy(DISTINCT_MONTH);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 2014-01-24
      • 2019-10-23
      相关资源
      最近更新 更多