group byÔÚsqlÖеÄÓ÷¨
group by Óï¾äÓÃÓÚ°´Ö¸¶¨ÁжÔÊý¾Ý¼¯¾ÙÐзÖ×飬²¢½«Í¬×éÊý¾Ý¾ÛºÏ¡£Óï·¨£ºselect ÁÐÃû1, ÁÐÃû2, …from ±íÃûgroup by ·Ö×éÁÐÃû;Ëü¿ÉÒÔÓë¾ÛºÏº¯ÊýÍŽáʹÓã¬ÀýÈç sum¡¢count¡¢avg£¬¶Ô×éÄÚÊý¾Ý¾ÙÐлã×Ü¡£Óŵã°üÀ¨¼ò»¯Êý¾ÝÆÊÎö¡¢Ê¶±ðģʽÇ÷ÊÆ£¬ÒÔ¼°Ìá¸ßÅÌÎÊÐÔÄÜ¡£
GROUP BY Óï¾äÔÚ SQL ÖеÄÓ÷¨
ʲôÊÇ GROUP BY Óï¾ä£¿
GROUP BY Óï¾äÓÃÓÚ½«Êý¾Ý¼¯ÖеÄÐзÖ×飬²¢½«Ïàͬ×éÖеÄÊý¾Ý¾ÛºÏΪһ¸öЧ¹ûÐС£
Óï·¨
SELECT ÁÐÃû1, ÁÐÃû2, ... FROM ±íÃû GROUP BY ·Ö×éÁÐÃû;
µÇ¼ºó¸´ÖÆ
·Ö×éÁÐÖ¸¶¨ÒªÆ¾Ö¤Æä·Ö×éÊý¾ÝµÄÁС£¿ÉÒÔ¶ÔÒ»¸ö»ò¶à¸öö¾ÙÐзÖ×é¡£
¾ÛºÏº¯Êý¿ÉÓÃÓÚ¾ÛºÏ×éÖеÄÊý¾Ý£¬ÀýÈç SUM¡¢COUNT¡¢AVG¡£
Ó÷¨
GROUP BY Óï¾äͨ³£Óë¾ÛºÏº¯ÊýÒ»ÆðʹÓã¬ÒÔÅÌËã×éÖÐÊý¾ÝµÄ»ã×ÜÖµ¡£ÀýÈ磺
-- ÅÌËãÏúÊÛ±íÖÐÿ¸ö²úÆ·µÄ×ÜÏúÁ¿ SELECT ProductName, SUM(Quantity) AS TotalQuantity FROM Sales GROUP BY ProductName;
µÇ¼ºó¸´ÖÆ
Ч¹û
GROUP BY Óï¾ä½«·µ»ØÒ»¸öЧ¹û¼¯£¬ÆäÖаüÀ¨·Ö×éÁÐÖÐÖ¸¶¨ÁеÄΨһֵÒÔ¼°¾ÛºÏÁеÄÅÌËãЧ¹û¡£
Óŵã
¼ò»¯Êý¾ÝÆÊÎö£¬½«Êý¾Ý×éÖ¯³ÉÓÐÒâÒåµÄ×é
ʶ±ðÊý¾ÝÖеÄģʽºÍÇ÷ÊÆ
Ìá¸ßÅÌÎÊÐÔÄÜ£¬ÓÉÓÚ·Ö×éÊý¾Ý±È´¦ÀíËùÓÐÐиüÓÐÓÃÂÊ
ʾÀý
¼ÙÉèÓÐÒ»ÕÅ°üÀ¨ÒÔÏÂÖ°Ô±Êý¾ÝµÄ±í£º
Name | Age | Gender |
---|---|---|
John | 25 | Male |
Mary | 30 | Female |
Bob | 40 | Male |
Alice | 28 | Female |
Tom | 35 | Male |
ÒÔÏ GROUP BY ÅÌÎʻὫְԱ°´ÐÔ±ð·Ö×飬²¢ÅÌËãÿ×éµÄÈËÊý£º
SELECT Gender, COUNT(*) AS Count FROM People GROUP BY Gender;
µÇ¼ºó¸´ÖÆ
Ч¹û£º
Gender | Count |
---|---|
Male | 3 |
Female | 2 |
ÒÔÉϾÍÊÇgroup byÔÚsqlÖеÄÓ÷¨µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡