当前位置: 代码迷 >> SQL >> [Teach Youself SQL in 十 Minutes] Grouping and Sorting
  详细解决方案

[Teach Youself SQL in 十 Minutes] Grouping and Sorting

热度:204   发布时间:2016-05-05 14:45:46.0
[Teach Youself SQL in 10 Minutes] Grouping and Sorting

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.

  相关解决方案