sqlÖеÄgroup byÓï¾äʲôÒâ˼
group by Óï¾äÓÃÓÚ½«Êý¾Ý°´Ö¸¶¨µÄÁлòÁÐ×éºÏ·Ö×飬²¢¶Ôÿ¸ö×éÖ´ÐоۺϺ¯Êý£¨ÈçÇóºÍ¡¢¼ÆÊý¡¢Çóƽ¾ùÖµ£©À´»ã×ÜÊý¾Ý¡£ÆäÓ﷨Ϊ£ºselect ÁÐ1, ÁÐ2, …from ±íÃûgroup by ·Ö×éÁÐ
SQL ÖÐµÄ GROUP BY Óï¾ä
GROUP BY Óï¾äÓÃÓÚ½«Êý¾Ý·Ö×飬²¢½«Ïàͬ×éÖеļͼ¾ÛºÏÔÚÒ»Æð¡£Í¨¹ý½«Êý¾Ý·ÖΪ²î±ðµÄ×飬Ëü¿ÉÒÔ×ÊÖúÎÒÃÇ»ã×ÜÐÅÏ¢¡¢Ê¶±ðģʽ²¢¼ò»¯Ð§¹û¡£
Óï·¨
SELECT ÁÐ1, ÁÐ2, ... FROM ±íÃû GROUP BY ·Ö×éÁÐ
µÇ¼ºó¸´ÖÆ
ÆäÖУº
ÁÐ1¡¢ÁÐ2¡¢… ÊÇÒª¼ìË÷µÄÁС£
±íÃû ÊÇÒª·Ö×éµÄ±í¡£
·Ö×éÁÐ ÊÇÒªÓÃÓÚ·Ö×éµÄÁлòÁеÄ×éºÏ¡£
¹¦Ð§
GROUP BY Óï¾äƾ֤ ·Ö×éÁÐ µÄÖµ½«Êý¾Ý·Ö×飬ȻºóÕë¶Ôÿ¸ö×éÖ´ÐоۺϺ¯Êý£¨Èç SUM()¡¢COUNT()¡¢AVG()£©£¬ÒÔ»ã×ÜÊý¾Ý¡£
ʾÀý
˼Á¿Ò»¸ö°üÀ¨Ñ§ÉúЧ¹ûµÄ±í£º
| ѧºÅ | ѧÉúÐÕÃû | ÊýѧЧ¹û | ÓïÎÄЧ¹û | |---|---|---|---| | 1 | À | 90 | 85 | | 2 | ÍõÇ¿ | 85 | 90 | | 3 | ÀîÃ÷ | 95 | 80 | | 4 | ÕÅΰ | 80 | 95 |
µÇ¼ºó¸´ÖÆ
ÈôÊÇÎÒÃÇÏ밴ѧÉúÐÕÃû·Ö×é²¢ÅÌËãÿλѧÉúµÄƽ¾ùÊýѧЧ¹û£¬¿ÉÒÔʹÓÃÒÔÏ GROUP BY Óï¾ä£º
SELECT ѧÉúÐÕÃû, AVG(ÊýѧЧ¹û) AS ƽ¾ùÊýѧЧ¹û FROM ѧÉúЧ¹û±í GROUP BY ѧÉúÐÕÃû
µÇ¼ºó¸´ÖÆ
Ч¹û½«ÊÇ£º
| ѧÉúÐÕÃû | ƽ¾ùÊýѧЧ¹û | |---|---| | À | 87.5 | | ÍõÇ¿ | 85.0 | | ÀîÃ÷ | 87.5 | | ÕÅΰ | 82.5 |
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇsqlÖеÄgroup byÓï¾äʲôÒâ˼µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡