首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

[Teach Youself SQL in 十 Minutes] Grouping and Sorting

2012-07-20 
[Teach Youself SQL in 10 Minutes] Grouping and SortingORDER BYGROUP BYSorts generated output.Groups

[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.

热点排行