|
ORDER BY |
GROUP BY |
|
Sorts generated output. |
Groups rows. The output might not be in group order, however. |
|
Any columns (even columns not selected) may be used. |
Only selected columns or expressions columns may be used, and every selected column expression must be used. |
|
Never required. |
Required if using columns (or expressions) with aggregate functions. |
More often than not, you will find that data grouped using GROUP BY will indeed be output in group order. But that is not always the case, and it is not actually required by the SQL specifications. Furthermore, even if your particular DBMS does, in fact, always sort the data by the specified GROUP BY clause, you might actually want it sorted differently. Just because you group data one way (to obtain group specific aggregate values) does not mean that you want the output sorted that same way. You should always provide an explicit ORDER BY clause as well, even if it is identical to the GROUP BY clause.
Don't Forget ORDER BY As a rule, anytime you use a GROUP BY clause, you should also specify an ORDER BY clause. That is the only way to ensure that data will be sorted properly. Never rely on GROUP BY to sort your data.
GROUPBY与ORDERBY用法解析
本文详细探讨了SQL中GROUPBY与ORDERBY的区别及使用场景。指出GROUPBY用于数据分组,但其结果不一定按组排序;ORDERBY则确保结果集按特定顺序排列。文章强调了即使使用GROUPBY进行分组时,也应明确指定ORDERBY来确保结果正确排序的重要性。
529

被折叠的 条评论
为什么被折叠?



