Search code examples
javascriptmysqlsqlnode.jsknex.js

sum is not working after taking union multiple column in knexjs mysql


I need a sum of 4 column ,I am doing that by first taking union then running sum

  db.select("gen-acute-sales-before-returns").table('sales')
  .union(function() {
    this.select("gen-acute-sales-after-returns").table('sales')
  })
  .union(function(){
    this.select("gen-chronic-sales-before-returns").table('sales')
  })
  .union(function(){
    this.select("gen-chronic-sales-after-returns").table('sales')
  })
  .sum({totalSales:"gen-acute-sales-before-returns"})
  .then(result => res.json(result))

Problem is that I am getting a union table but sum is not working


Solution

  • I just add general knex debugging guidance here, since the question is pretty ambiguous.

    Check out what query is generated by calling .toSQL() for the query builder. Then you can see if the generated query has something wrong.

    console.log(
      db.select("gen-acute-sales-before-returns").table('sales')
      .union(function() {
        this.select("gen-acute-sales-after-returns").table('sales')
      })
      .union(function(){
        this.select("gen-chronic-sales-before-returns").table('sales')
      })
      .union(function(){
        this.select("gen-chronic-sales-after-returns").table('sales')
      })
      .sum({totalSales:"gen-acute-sales-before-returns"}).toSQL().sql
    );
    

    It is completely possible that there is bug in knex's union method (wouldn't be the first time).