如何将SQL查询返回的列的列名通过传入字符串变量的方式重命名

假如我现在有这样一张表:

symbol = take(`GE,6) join take(`MSFT,6) join take(`F,6)
date=take(take(2017.01.03,2) join take(2017.01.04,4), 18)
price=31.82 31.69 31.92 31.8  31.75 31.76 63.12 62.58 63.12 62.77 61.86 62.3 12.46 12.59 13.24 13.41 13.36 13.17
volume=2300 3500 3700 2100 1200 4600 1800 3800 6400 4200 2300 6800 4200 5600 8900 2300 6300 9600
t1 = table(symbol, date, price, volume);
t1;

attachments-2022-11-IQA0Dquy636b32f72265d.png

现在需要查询symbol为MSFT的数据,然后根据日期做一些聚合计算,比如按天聚合做avg(price)和sum(volume),但是我又想通过传入字符串变量的方式重命名返回的查询列,请问有办法实现吗?

请先 登录 后评论

1 个回答

Jason Tang - 时序数据库技术支持

可以使用DolphinDB的元编程功能实现上述需求,元编程教程链接:https://gitee.com/dolphindb/Tutorials_CN/blob/master/meta_programming.md

可以参考以下写法:

name1 = `avgPrice
name2 = `sumVol
whereConditions = [<symbol=`MSFT>,<volume>x>]
sql(select=(sqlColAlias(<avg(price)>, name1), sqlColAlias(<sum(volume)>, name2)), from=t1, groupBy=sqlCol(`date)).eval()

返回结果如下
attachments-2022-11-ZU4DWf3M636b33deefb1a.png
请先 登录 后评论