📜  SQL中order by和group by子句的区别

📅  最后修改于: 2021-09-28 09:49:23             🧑  作者: Mango

1. 订购方式:
按关键字排序按升序或降序对结果集进行排序。该子句默认按升序对结果集进行排序。为了按降序对结果集进行排序,使用了DESC关键字。

按语法排序 –

SELECT column_1, column_2, column_3...........
FROM Table_Name
ORDER BY column_1, column_2, column_3....... ASC|DESC;


Table_Name: Name of the table.
ASC: keyword for ascending order
DESC: keyword for descending order 

2. 分组方式:
Group by 语句用于对具有相同值的行进行分组。它经常与聚合函数一起使用,例如:AVG()、MAX()、COUNT()、MIN() 等。 关于 group by 子句要记住的一件事是元组根据属性值之间的相似性进行分组元组。

按语法分组 –

SELECT function_Name(column_1), column_2
FROM Table_Name
WHERE condition
GROUP BY column_1, column_2
ORDER BY column_1, column_2; 

function_Name:聚合函数的名称,例如:

SUM(), AVG(), COUNT() etc.

Table_Name: Name of the table. 

让我们看看 Order by 和 group by 子句之间的区别:-

S.NO GROUP BY ORDER BY
1. Group by statement is used to group the rows that have the same value. Whereas Order by statement sort the result-set either in ascending or in descending order.
2. It may be allowed in CREATE VIEW statement. While it does not use in CREATE VIEW statement.
3. In select statement, it is always used before the order by keyword. While in select statement, it is always used after the group by keyword.
4. Attribute cannot be in the group by statement under aggregate function. Whereas in order by statement, attribute can be under aggregate function.
5. In group by clause, the tuples are grouped based on the similarity between the attribute values of tuples. Whereas in order by clause, the result-set is sorted based on ascending or descending order.
6. Group by controls the presentation of tuples(rows). While order by clause controls the presentation of columns.