
group by 和order by 的配合使用
group by 和order by 的配合使用
SELECT event_key,MAX(stock) as stock,pro_code from act_lottery_stock GROUP BY event_key ORDER BY stock desc limit 3;
其中取最大库存stock进行排序
GROUP BY和ORDER BY同时存在的情况是,ORDER BY对GROUP BY后的结果再进行排序的,所以ORDER BY后面的排序字段需要在SELECT里出现的,即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]