我正在尝试使用DBIx :: Class ResultSet来构建:
SELECT commitment_sub_activity_id, SUM(commitment_amount_in_usd)
FROM query_commitments_financials
GROUP BY (commitment_sub_activity_id)
这是我试图用来执行此操作的Perl代码:
my $sub_activity_commitments = $schema->resultset('QueryCommitmentsFinancial')->search(undef,
{
select => [
'commitment_sub_activity_id',
{ sum => 'commitment_amount_in_usd' }
],
as => [qw/commitment_sub_activity_id total_commitment_in_usd/],
'group_by' => [qw/commitment_sub_activity_id/],
});
据我了解,select
属性应该阻止任何未列出的字段出现在SELECT
语句中。但是,SQL语句DBIx :: Class创建为:
SELECT
me.source_id, me.commitment_id,
me.commitment_obligation_id, me.commitment_sub_activity_id,
me.commitment_task_code, me.commitment_status,
me.commitment_date, me.commitment_currency_id,
me.commitment_amount, me.exchange_rate,
me.commitment_amount_in_usd, me.commitment_sub_activity_id,
SUM( commitment_amount_in_usd )
FROM query_commitments_financials me
GROUP BY commitment_sub_activity_id
此查询导致我的RDBMS抛出错误,因为这些意外的列都需要包含在GROUP BY中。
获取DBIx :: Class ResultSet以构建此聚合查询的正确方法是什么?
更新:按要求提供QueryCommitmentsFinancial的ResultClass定义。我使用DBIx :: Class :: Schema :: Loader来创建它,所以我删除了POD。
use utf8;
package IPMS::Schema::Result::QueryCommitmentsFinancial;
use strict;
use warnings;
use base 'DBIx::Class::Core';
__PACKAGE__->load_components("InflateColumn::DateTime");
__PACKAGE__->table_class("DBIx::Class::ResultSource::View");
__PACKAGE__->table("query_commitments_financials");
__PACKAGE__->add_columns(
"source_id",
{ data_type => "nvarchar", is_nullable => 1, size => 52 },
"commitment_id",
{ data_type => "nvarchar", is_nullable => 1, size => 51 },
"commitment_obligation_id",
{ data_type => "nvarchar", is_nullable => 1, size => 45 },
"commitment_sub_activity_id",
{ data_type => "integer", is_nullable => 0 },
"commitment_task_code",
{ data_type => "nchar", is_nullable => 0, size => 7 },
"commitment_status",
{ data_type => "nvarchar", is_nullable => 0, size => 10 },
"commitment_date",
{ data_type => "datetime", is_nullable => 1 },
"commitment_currency_id",
{ data_type => "integer", is_nullable => 0 },
"commitment_amount",
{ data_type => "money", is_nullable => 1 },
"exchange_rate",
{ data_type => "double precision", is_nullable => 1 },
"commitment_amount_in_usd",
{ data_type => "money", is_nullable => 1 },
);
1;