sqlÖÐÓÃÓÚ·Ö×éÅÌÎʵÄÓï¾ä
sql ÖÐÓÃÓÚ·Ö×éÅÌÎʵÄÓï¾äÊÇ group by£¬Ëüƾָ֤¶¨Áлò±í´ïʽ¶ÔÊý¾Ý¼¯¾ÙÐзÖ×飬²¢ÅÌËãÿ¸ö×éµÄ¾ÛºÏÖµ£¬ÈçÇóºÍ»òÇóƽ¾ùÖµ¡£ÀýÈ磬group by product_name ºÍ sum(sales_amount) ¿ÉÒÔÅÌËãÿ¸ö²úÆ·µÄ×ÜÏúÊ۶±¬·¢ÒÔÏÂЧ¹û£ºproduct_name, total_sales£¬ÆäÖÐ product_name ÊÇ·Ö×éÁУ¬total_sales ÊÇÿ¸ö×éµÄÏúÊÛ¶î×ܺ͡£group by ÅÌÎÊ¿ÉÒÔǶÌ×ÒÔ½¨Éè¸üÖØ´óµÄ·Ö×飬ÀýÈ磬ǶÌ× group by product_ca
SQL ÖÐÓÃÓÚ·Ö×éÅÌÎʵÄÓï¾ä
·Ö×éÅÌÎÊÊÇÒ»ÖÖ½«Êý¾Ý¼¯Æ¾Ö¤Ìض¨Áлò±í´ïʽ¾ÙÐзÖ×飬²¢ÅÌËãÿ¸ö×éµÄ¾ÛºÏÖµ£¨ÈçÇóºÍ¡¢Çóƽ¾ùÖµ£©µÄÅÌÎÊ¡£ÔÚ SQL ÖУ¬ÓÃÓÚ·Ö×éÅÌÎʵÄÖ÷ÒªÓï¾äÊÇ GROUP BY¡£
GROUP BY Óï¾ä
GROUP BY Óï¾äµÄ»ù±¾Óï·¨ÈçÏ£º
SELECT ÁÐÃû, ¾ÛºÏº¯Êý(ÁÐÃû) FROM table_name GROUP BY ÁÐÃû
µÇ¼ºó¸´ÖÆ
ÆäÖУº
ÁÐÃû£ºÐèÒª·Ö×éµÄÁлò±í´ïʽ¡£
¾ÛºÏº¯Êý£ºÓ¦ÓÃÓÚÿ¸ö×éµÄ¾ÛºÏº¯Êý£¬Èç SUM()¡¢AVG()¡¢COUNT()¡£
ʾÀý
˼Á¿Ò»¸öÃûΪ “sales” µÄ±í£¬ÆäÖаüÀ¨ÒÔÏÂÁУº
product_id | product_name | sales_amount |
---|---|---|
1 | Apple | 100 |
2 | Orange | 200 |
3 | Banana | 300 |
4 | Apple | 250 |
5 | Orange | 150 |
ÒªÅÌËãÿ¸ö²úÆ·µÄ×ÜÏúÊ۶¿ÉÒÔʹÓÃÒÔÏ GROUP BY ÅÌÎÊ£º
SELECT product_name, SUM(sales_amount) FROM sales GROUP BY product_name;
µÇ¼ºó¸´ÖÆ
ÅÌÎÊЧ¹û½«ÈçÏÂËùʾ£º
product_name | total_sales |
---|---|
Apple | 350 |
Orange | 350 |
Banana | 300 |
ǶÌ× GROUP BY
GROUP BY ÅÌÎÊ¿ÉÒÔǶÌ×ÔÚÆäËûÅÌÎÊÖУ¬ÒÔ½¨Éè¸üÖØ´óµÄ·Ö×é¡£ÀýÈ磬ҪÅÌËãÿ¸ö²úÆ·ÖÖ±ðºÍÿ¸ö²úÆ·µÄ×ÜÏúÊ۶¿ÉÒÔʹÓÃÒÔÏÂǶÌ× GROUP BY ÅÌÎÊ£º
SELECT product_category, product_name, SUM(sales_amount) FROM sales GROUP BY product_category, product_name;
µÇ¼ºó¸´ÖÆ
ÅÌÎÊЧ¹û½«ÈçÏÂËùʾ£º
product_category | product_name | total_sales |
---|---|---|
Fruits | Apple | 350 |
Fruits | Banana | 300 |
Fruits | Orange | 350 |
ÒÔÉϾÍÊÇsqlÖÐÓÃÓÚ·Ö×éÅÌÎʵÄÓï¾äµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡