使用node.js中的alasql连接两个包含where子句的select语句

时间:2018-05-31 16:17:45

标签: javascript node.js alasql

我在node.js中使用alasql,但我无法使用联接。

这里有虚拟数据:

x = [ 
{ date: 20180501, price: 23, product: 'x' },
{ date: 20180501, price: 46, product: 'y' },
{ date: 20180502, price: 29, product: 'x' },
{ date: 20180502, price: 50, product: 'y' },
{ date: 20180503, price: 22, product: 'x' },
{ date: 20180503, price: 43, product: 'y' },
{ date: 20180504, price: 21, product: 'x' },
{ date: 20180504, price: 43, product: 'y' },
{ date: 20180505, price: 26, product: 'x' },
{ date: 20180505, price: 48, product: 'y' }]

我希望每天都能得到产品y和产品y的价格之间的比率。所以,我想要的输出是:

desiredOutput = [ 
{ date: 20180501, price_ratio: 46/23},  
{ date: 20180502, price_ratio: 50/29},  
{ date: 20180503, price_ratio: 43/22},
{ date: 20180504, price_ratio: 43/21},
{ date: 20180505, price_ratio: 48/26}]

我试图通过以下查询得到这个:

alasql("select date, price_y/price_x as price_ratio from (select date, price as price_y from ? where product='y') as y join (select date, price as price_x from ? where product='x') as x on x.date=y.date", [x,x])

但我无法让它发挥作用。它没有崩溃或任何事情,但我只得到price_x,而不是比率。这就是我得到的:

[ 
{ date: 20180501, price_x: 23 },
{ date: 20180502, price_x: 29 },
{ date: 20180503, price_x: 22 },
{ date: 20180504, price_x: 21 },
{ date: 20180505, price_x: 26 } ]

我可以通过分别运行和存储每个子查询,然后使用这些对象执行连接来获得所需的结果,但我想知道如何在一次调用中只使用嵌套的子查询。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

/* to get produt x and y prices for each date */
const res = alasql("select date, sum(case when product='x' then price else null end) as price_x, sum(case when product='y' then price else null end) as price_y from ? group by date", [x])

/* to get ratio */
const res1 = alasql("select date, concat(price_y, '/', price_x) price_ratio from (select date, sum(case when product='x' then price else null end) as price_x, sum(case when product='y' then price else null end) as price_y from ? group by date)", [x])

console.log(res)
console.log(res1)

编辑:添加DEMO