I am generating a report using select query and group by in cakephp in SQL server

Viewed 91

I am selecting the sum from OrderProduct using select query and used group. In local its Mysql but in server its Sql server. In local there is no error but in server there is error:

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.

My controller code is :

$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');
1 Answers

Your query has a grouping using "product_id" field from "OrderProduct" so you must specify which of the values should be returned from a field that is not grouped.

You will do this using an aggregate function as the error message suggests:

MIN, MAX, SUM

So you can change your code to get the max value:

MAX(Products.product_name)

Or change the group to:

Products.id
Related