Group By in Laravel with SQL Server

1

I have the following query in Laravel through query builder:

$objective_risk = DB::table('objective_risk')
              ->join('objectives','objectives.id','=','objective_risk.objective_id')
              ->join('risks','risks.id','=','objective_risk.risk_id')
              ->where('objectives.organization_id','=',(int)$org)
              ->groupBy('risks.id')
              ->orderBy('risks.name')
              ->select('risks.name','objective_risk.id as riskid')
              ->get();

This query works perfectly connecting me to MySQL, but now I need it to work for me in SQL Server, which gives me the following error:

SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]
La columna 'risks.name' de la lista de selección no es válida, porque no está contenida en 
una función de agregado ni en la cláusula GROUP BY. (SQL: select [risks].[name], [risks].[id] 
from [objective_risk] inner join [objectives] on [objectives].[id] = [objective_risk].
[objective_id] inner join [risks] on [risks].[id] = [objective_risk].[risk_id] where 
[objectives].[organization_id] = 28 group by [risks].[id] order by [risks].[name] asc)

In the background I have a table of risks and another of objectives (in relation to many to many), and I want to obtain the id of the relation (objective_risk.id) and the name of the risk, and I try to do the grouping by the id of the risk (considering that it is a many-to-many relation so that they do not repeat themselves), which in MySQL works perfect but not in SQL Server.

I hope you can orient me a bit.

    
asked by Felipe Herrera 28.03.2017 в 15:14
source

1 answer

0

Look, you are selecting two fields risk.name and objective_risk.id but you are grouping by one, that in SQL server is not valid, unless you use an aggregation function on risks.name, but I understand that it is not the case. As you suggested @Shaz, you have to add risks.name to the Group by.

    
answered by 28.03.2017 в 16:38