Group By和Order By的总结
1、Group By 语句中:select指定的字段必须是“分组依据字段”,其他字段若想出现在select中则必须包含在聚合函数中。
例如:
select [col1], avg([col2]) from [tb] group by [col1];
2、Order By和Group By 一起使用时需要注意: ORDER BY 子句中的列必须包含在聚合函数或 GROUP BY 子句中。
例如:
SELECT
[col1] ,[col2],
MAX
([col3])
FROM
[tb]
GROUP
BY
[col1] ,[col2]
ORDER
BY
[col1] ,[col2] ,
MAX
([col3])
SELECT
[col1] ,[col2],
MAX
([col3])
AS
[col3]
FROM
[tb]
GROUP
BY
[col1] ,[col2]
ORDER
BY
[col1] ,[col2] ,[col3]
SELECT
[col1] ,[col2]
FROM
[tb]
GROUP
BY
[col1] ,[col2] ,[col3]
ORDER
BY
[col1] ,[col2] ,[col3]