aryan87
aryan87

Reputation: 119

How to multiply and then add the values of two table columns using Knex.js?

I need to multiply the values from column_A and column_B of a table table_A and then add them using knex.js. Following is the code which I am using to achieve it, which is resulting in an error:

knex().from('table_A').raw('sum(column_A * column_B) as column_c')

Any pointers to what I am missing here?

Upvotes: 0

Views: 2807

Answers (3)

Suresh Kumar Amrani
Suresh Kumar Amrani

Reputation: 935

This is working for me . You can use knexraw query to get object

async getTotal(user_id){
 return await
                    this.knex.raw('SELECT sum(cart.qty * product_item.price) as sub_total\n' +
                        'FROM cart \n' +
                        'JOIN product_item ON cart.product_item_id = product_item.id\n' +
                        'WHERE cart.user_id=39');
}

Upvotes: 0

Fazal Rasel
Fazal Rasel

Reputation: 4526

knex('table_a')
  .columns([
    knex.raw('sum(column_a * column_b) as column_c')
  ])
  .first()
  .then((rows) => {
    console.log(rows); //log { column_c: 500 }
  });

Upvotes: 1

Mikael Lepistö
Mikael Lepistö

Reputation: 19728

Maybe this works better:

knex('table_A').select(
  knex.raw('sum(?? * ??) as ??', ['column_A', 'column_B', 'column_C'])
)

Upvotes: 2

Related Questions