如何用“order by”和“group by”使用不同的列编写SQL server查询?

时间:2021-10-13 15:45:47

I want to write a query in SQL Server using order by and group by in the same query but different columns:

我想在SQL Server中使用order by和group by在同一个查询但不同的列中编写查询:

SELECT map.route_id FROM map GROUP BY map.route_id ORDER BY (map.orderOfcity); 

It gives this error :

它给出了这个错误:

Msg 8127, Level 16, State 1, Line 1 Column "map.orderOfcity" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

消息8127,级别16,状态1,行1列“map.orderOfcity”在ORDER BY子句中无效,因为它不包含在聚合函数或GROUP BY子句中。

I realized that I have to make ORDER BY and GROUP BY for the same column but that doesn't suit for me, what should I do instead?

我意识到我必须为同一列创建ORDER BY和GROUP BY但这不适合我,我该怎么做呢?

1 个解决方案

#1


1  

Assuming that orderOfCity is a number, you can do this:

假设orderOfCity是一个数字,你可以这样做:

SELECT map.route_id
FROM map 
GROUP BY map.route_id
ORDER BY MIN(map.orderOfcity); 

#1


1  

Assuming that orderOfCity is a number, you can do this:

假设orderOfCity是一个数字,你可以这样做:

SELECT map.route_id
FROM map 
GROUP BY map.route_id
ORDER BY MIN(map.orderOfcity);