Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

node.js - Referencing an aliased column in the same select statement with Knex/Sqlite

I'm relatively new to SQL and have it a wall. I'm using Knex with Sqlite and I have a table that's comprised of all sales and it contains the sale amount, the salesperson, and the product category. I'd like to have a statement that gets this information, but then creates another column that is the percentage difference between the sales amount of all sales and the sales of that category.

So far, I have this working fine:

const result = await knex('tablename')
  .select('salesperson')
  .sum('salesvolume')
  .select(
    knex.raw("sum(CASE category = 'myCategory' THEN salesvolume ELSE 0 END) AS categoryvolume"),
  )
  .groupBy('salesperson')
  .orderBy('salesvolume');
// example of result:
// [
//   {
//     salesperson: 'Jim A',
//     salesvolume: 1000,
//     categoryvolume: 400,
//   },
//   {
//     salesperson: 'Sarah B',
//     salesvolume: 200,
//     categoryvolume: 50,
//   }
// ];

In an ideal world, I'd be able to simply add another raw call in my select chain, something like:

const result = await knex('tablename')
  .select('salesperson')
  .sum('salesvolume')
  .select(
    knex.raw("sum(CASE category = 'myCategory' THEN salevolume ELSE 0 END) AS categoryvolume"),
    knex.raw('(sum(categoryvolume) / sum(salesvolume) AS categorypercentage'),
  )
  .groupBy('salesperson')
  .orderBy('salevolume');
// I'm aiming to get:
// [
//   {
//     salesperson: 'Jim A',
//     salesvolume: 1000,
//     categoryvolume: 400,
//     categorypercentage: .4,
//   },
// ];

But that's not going to work since categoryvolume is a column that is aliased and created in the same select statement and can not be referenced. Is there another way I can go about this? I'm feeling like I just am not thinking about it correctly.

Thanks for any and all help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...