我在 SQL 服务器的 cakephp 中使用 select 查询和分组生成报告
I am generating a report using select query and group by in cakephp in SQL server
我正在 select 使用 select 查询和使用组计算 OrderProduct 的总和。在本地是 Mysql 但在服务器是 Sql 服务器。在本地没有错误,但在服务器中有错误:
2020-07-24 10:21:35 Error: [PDOException] SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column 'products.product_name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
我的控制器代码是:
$getQuery = $this->OrderProduct
->find('all', [
'contain' => [
'Orders' => ['PaymentMethods'],
'Products' => ['ProductType']
]
])
->select([
'product_name' => 'Products.product_name',
'count' => 'SUM(OrderProduct.qty)',
'actual_rate' => 'SUM(OrderProduct.actual_rate)',
'order_date' => 'Orders.order_date',
'payment_gateway' => 'PaymentMethods.payment_gateway'
])
->where($conditions);
$getQuery->where([
'Products.is_deleted' => 'n'
]);
$getQuery->matching('Products.ProductType');
$getQuery->where([
'ProductType.slug' => $searchparams['product_type_id']
]);
$getQuery->where([
'Orders.order_status NOT IN' => ['payment_pending']
]);
$getAll = $getQuery->group('OrderProduct.product_id');
您的查询使用“OrderProduct”中的“product_id”字段进行了分组,因此您必须指定应从未分组的字段中返回哪些值。
您将按照错误消息的建议使用聚合函数执行此操作:
MIN, MAX, SUM
因此您可以更改代码以获得最大值:
MAX(Products.product_name)
或将群组更改为:
Products.id
我正在 select 使用 select 查询和使用组计算 OrderProduct 的总和。在本地是 Mysql 但在服务器是 Sql 服务器。在本地没有错误,但在服务器中有错误:
2020-07-24 10:21:35 Error: [PDOException] SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column 'products.product_name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
我的控制器代码是:
$getQuery = $this->OrderProduct
->find('all', [
'contain' => [
'Orders' => ['PaymentMethods'],
'Products' => ['ProductType']
]
])
->select([
'product_name' => 'Products.product_name',
'count' => 'SUM(OrderProduct.qty)',
'actual_rate' => 'SUM(OrderProduct.actual_rate)',
'order_date' => 'Orders.order_date',
'payment_gateway' => 'PaymentMethods.payment_gateway'
])
->where($conditions);
$getQuery->where([
'Products.is_deleted' => 'n'
]);
$getQuery->matching('Products.ProductType');
$getQuery->where([
'ProductType.slug' => $searchparams['product_type_id']
]);
$getQuery->where([
'Orders.order_status NOT IN' => ['payment_pending']
]);
$getAll = $getQuery->group('OrderProduct.product_id');
您的查询使用“OrderProduct”中的“product_id”字段进行了分组,因此您必须指定应从未分组的字段中返回哪些值。
您将按照错误消息的建议使用聚合函数执行此操作:
MIN, MAX, SUM
因此您可以更改代码以获得最大值:
MAX(Products.product_name)
或将群组更改为:
Products.id