如何使用查询选择聚合字段?

时间:2014-04-01 10:33:55

标签: axapta x++ dynamics-ax-2012

我正在尝试使用addselectionfield选择4个字段。来自那4个字段2的是聚合(和)字段。

我正在做以下事情:

            date fromDate = systemDateGet();
            date toDate = (systemDateGet() + 25);
            query          = new Query();
            qbds           = query.addDataSource(tableNum(MyTable));
            qbds.addSelectionField(fieldNum(MyTable, DateField));
            qbds.addSelectionField(fieldNum(MyTable, USDAmountField), SelectionField::Sum);
            qbds.addSelectionField(fieldNum(MyTable, CurrencyNameField));
            qbds.addSelectionField(fieldNum(MyTable, EURAmountField), SelectionField::Sum);
            qbr            = qbds.addRange(fieldNum(MyTable, DateField));
            qbr.value(queryRange(fromDate, toDate));

            queryRun       = new QueryRun(query);

在调试时,我在queryRun中得到以下select语句:

SELECT SUM(EURAmountField) FROM MyTable(MyTable_1)
WHERE ((DateField >= {ts '2014-04-01 00:00:00.000'}
AND DateField <= {ts'2014-04-26 00:00:00.000'}))

那么为什么它只选择最后一个addSelectionField以及我必须做什么来获取我在addSelectionFields中编写的所有字段的原因是什么?

1 个答案:

答案 0 :(得分:5)

没有理由(我能想到)......这应该有效,应该将选择域添加到querybuilddatasource中。尝试同步,编译和/或重新启动客户端/ aos。

您还必须做的是在要选择的字段上添加分组字段。否则AX将不知道选择什么值,因为多个记录可以具有不同的值。例如,要选择CurrencyNameField,请将其添加为选择字段,并使用:

qbds.addGroupByField(fieldNum(MyTable, CurrencyNameField)); 

然后您将获得CurrencyNameField字段中的数据,但您将获得每个货币名称的总和。

这似乎有效:

Query query;
QueryBuildDataSource qbds;
QueryBuildRange qbr;
QueryRun queryrun;

date fromDate = systemDateGet();
date toDate = (systemDateGet() + 25);
query          = new Query();
qbds           = query.addDataSource(tableNum(MyTable));
qbds.addGroupByField(fieldNum(MyTable, DateField));
qbds.addGroupByField(fieldNum(MyTable, CurrencyNameField));
qbds.addSelectionField(fieldNum(MyTable, DateField));
qbds.addSelectionField(fieldNum(MyTable, CurrencyNameField));
qbds.addSelectionField(fieldNum(MyTable, EURAmountField), SelectionField::Sum);
qbds.addSelectionField(fieldNum(MyTable, USDAmountField), SelectionField::Sum);
qbr            = qbds.addRange(fieldNum(MyTable, DateField));
qbr.value(queryRange(fromDate, toDate));

queryRun       = new QueryRun(query);

queryrun包含:

SELECT DateField, CurrencyNameField, SUM(EURAmountField), SUM(USDAmountField) 
FROM MyTable(MyTable_1) GROUP BY MyTable.DateField, MyTable.CurrencyNameField 
WHERE ((DateField>={ts '2014-04-01 00:00:00.000'} 
AND DateField<={ts '2014-04-26 00:00:00.000'}))