Oracle group by¼°ÆäÈô¸ÉÏà¹Øº¯ÊýµÄһЩ˵Ã÷
http://blog.csdn.net/roland_wg/archive/2009/07/03/4319323.aspx
OracleµÄgroup by³ýÁË»ù±¾Ó÷¨ÒÔÍ⣬»¹ÓÐ3ÖÖÀ©Õ¹Ó÷¨£¬·Ö±ðÊÇrollup¡¢cube¡¢grouping sets¡£
¼ÙÉèÓÐÒ»¸ö±ítest£¬ÓÐA¡¢B¡¢C¡¢D¡¢E5ÁС£
1£© Èç¹ûʹÓÃgroup by rollup(A,B,C)£¬Ê×ÏÈ»á¶Ô(A¡¢B¡¢C)½øÐÐGROUP BY£¬È»ºó¶Ô(A¡¢B)½øÐÐGROUP BY£¬È»ºóÊÇ(A)½øÐÐGROUP BY£¬×îºó¶ÔÈ«±í½øÐÐGROUP BY²Ù×÷¡£roll upµÄÒâ˼ÊÇ“¾íÆ𔣬ÕâÒ²¿ÉÒÔ°ïÖúÎÒÃÇÀí½âgroup by rollup¾ÍÊǶÔÑ¡ÔñµÄÁдÓÓÒµ½×óÒÔÒ»´ÎÉÙÒ»Áеķ½Ê½½øÐÐgroupingÖ±µ½ËùÓÐÁж¼È¥µôºóµÄgrouping(Ò²¾ÍÊÇÈ«±ígrouping)£¬¶ÔÓÚn¸ö²ÎÊýµÄrollup£¬ÓÐn+1´ÎµÄgrouping¡£ÒÔÏÂ2¸ösqlµÄ½á¹û¼¯ÊÇÒ»ÑùµÄ£º
Select A,B,C,sum(E) from test group by rollup(A,B,C)ºÍ
Select A,B,C,sum(E) from test group by A,B,C
union all
Select A,B,null,sum(E) from test group by A,B
union all
Select A,null,null,sum(E) from test group by A
union all
Select null,null,null,sum(E) from test
2) cubeµÄÒâ˼ÊÇÁ¢·½£¬¶ÔcubeµÄÿ¸ö²ÎÊý£¬¶¼¿ÉÒÔÀí½âΪȡֵΪ²ÎÓëgroupingºÍ²»²ÎÓëgroupingÁ½¸öÖµµÄÒ»¸öά¶È£¬È»ºóËùÓÐά¶ÈÈ¡Öµ×éºÏµÄ¼¯ºÏ¾ÍÊÇgroupingµÄ¼¯ºÏ£¬¶ÔÓÚn¸ö²ÎÊýµÄcube£¬ÓÐ2^n´ÎµÄgrouping¡£Èç¹ûʹÓÃgroup by cube(A,B,C), £¬ÔòÊ×ÏÈ»á¶Ô(A¡¢B¡¢C)½øÐÐGROUP BY£¬È»ºóÒÀ´ÎÊÇ(A¡¢B)£¬(A¡¢C)£¬(A)£¬(B¡¢C)£¬(B)£¬(C)£¬×îºó¶ÔÈ«±í½øÐÐGROUP BY²Ù×÷£¬Ò»¹²ÊÇ2^3=8´Îgrouping¡£Í¬rollupÒ»Ñù£¬Ò²¿ÉÒÔÓûù±¾µÄgroup by¼ÓÉϽá¹û¼¯µÄunion allд³öÒ»¸öÓëgroup by cube½á¹û¼¯ÏàͬµÄsql£º
Select A,B,C,sum(E) from test group by cube(A,B,C)£»
Select A,B,C,sum(E) from test group by A,B,C
union all
Select A,B,null,sum(E) from test group by A,B
union all
Select A,null,C,sum(E) from test group by A,C
union all
Select A,null,null,sum(E) from test group by A
union all
Select null,B,C,sum(E) from test group by B,C
union all
Select null,B,null,sum(E) from test group by B
union all
Select null,null,C,sum(E) from test group by C
union all
Select null,null,null,sum(E) from test
3) grouping sets¾ÍÊǶԲÎÊýÖеÄÿ¸ö²ÎÊý×ögrouping£¬Ò²¾ÍÊÇÓм¸¸ö²ÎÊý×ö¼¸´Îgrouping, ÀýÈçʹÓÃgroup by grouping sets(A,B,C)£¬Ôò¶Ô(A),(B),(C)½øÐÐgroup by£¬È
Àí½âoracleÖÐÁ¬½ÓºÍ»á»° 1. ¸ÅÄͬ£º¸ÅÄͬ£º
Á¬½ÓÊÇÖ¸ÎïÀíµÄÍøÂçÁ¬½Ó¡£
ÔÚÒѽ¨Á¢µÄÁ¬½ÓÉÏ£¬½¨Á¢¿Í»§¶ËÓëoracleµÄ»á»°£¬ÒÔºó¿Í»§¶ËÓëoracleµÄ½»»¥¶¼ÔÚÒ»¸ö»á»°»·¾³ÖнøÐС£
2. ¹ØϵÊǶà¶Ô¶à£º
Ò»¸öÁ¬½ÓÉÏ¿ÉÒÔ½¨Á¢0¸ö£¬1¸ö£¬2¸ö£¬¶à¸ö»á»°¡£
OracleÔÊÐí´æÔÚÕâÑùµÄ»á»°£¬¾ÍÊÇʧȥÁËÎïÀíÁ¬½ÓµÄ»á»°¡£
3. ¸ÅÄîÓ¦Ó㺸 ......
˵Ã÷:ÏÂÎÄÖеÄһЩ˵Ã÷ºÍʾÀý´úÂëÕª×ÔCSDN,Ë¡²»Ò»Ò»Ö¸Ã÷³ö´¦,ÔÚ´ËÒ»²¢¶ÔÏà¹Ø×÷Õß±íʾ¸Ðл!
¡¡¡¡1 Óï·¨
¡¡¡¡ÔÚOracleÖУ¬¿ÉÒÔ´´½¨ÒÔÏÂÁ½ÖÖÁÙʱ±í£º
¡¡¡¡1) »á»°ÌØÓеÄÁÙʱ±í
¡¡¡¡CREATE GLOBAL TEMPORARY ( )
¡¡¡¡ON COMMIT PRESERVE ROWS£»
¡¡¡¡2) ÊÂÎñÌØÓеÄÁÙʱ±í
¡¡¡¡CREATE GLOBAL TEMPORARY ( )
¡¡¡¡O ......