sqlÖÐrownumberºÍrankÇø±ð
row_number ºÍ rank ¶¼ÊÇÓÃÓÚ¶Ô sql Ч¹û¼¯ÅÅÐòºÍ±àºÅµÄº¯Êý¡£row_number °´²åÈë˳ÐòΪÐзÖÅÉÒ»Á¬ÕûÊý£¬¶ø rank Ϊ¾ßÓÐÏàֵͬµÄÐзÖÅÉÏàͬµÄÅÅÃû£¬²¢ÖØбàºÅºóÐøÐÐÒÔ×èÖ¹Öظ´¡£row_number ʼÖÕ·µ»ØÒ»Á¬ÕûÊý£¬¶ø rank ¿ÉÒÔ·µ»ØÏàͬ»ò²î±ðµÄÅÅÃû£¬Ïêϸȡ¾öÓÚÐеÄÖµ¡£row_number ÓÃÓÚ°´²åÈë˳Ðò¶ÔÐбàºÅ»ò¶Ô»ùÓÚÌض¨Ìõ¼þµÄÒ»Á¬×Ó¼¯±àºÅ£¬¶ø rank ÓÃÓÚ¶ÔÐÐÅÅÃû»òÈ·¶¨¾ßÓÐÏàֵͬµÄÐеÄÏà¶ÔλÖá£
ROW_NUMBER ºÍ RANK ÔÚ SQL ÖеÄÇø±ð
ROW_NUMBER ºÍ RANK ¶¼ÊÇ SQL ÖÐÓÃÓÚ¶ÔЧ¹û¼¯¾ÙÐÐÅÅÐòºÍ±àºÅµÄº¯Êý¡£ËäÈ»Á½Õ߶¼ÓÐÏàËƵÄÄ¿µÄ£¬µ«ËüÃÇÔÚʵÏÖÉϺÍЧ¹ûÉϱ£´æһЩҪº¦²î±ð¡£
ʵÏֵIJî±ð
ROW_NUMBER£º Ϊÿ¸öÐзÖÅÉÒ»¸öΨһµÄÕûÊý£¬°´ÐвåÈëµÄ˳Ðò¾ÙÐбàºÅ¡£
RANK£º Ϊ¾ßÓÐÏàֵͬµÄÐзÖÅÉÏàͬµÄÅÅÃû£¬µ«¶ÔºóÐøÐоÙÐÐÖØбàºÅ£¬ÒÔÈ·±£Ã»ÓÐÖظ´µÄÅÅÃû¡£
Ч¹ûµÄ²î±ð
ROW_NUMBER£º ʼÖÕ·µ»ØÒ»Á¬µÄÕûÊý£¬¶ø²»Ë¼Á¿ÐеÄÖµ¡£Í³Ò»ÅÅÃûϵÄËùÓÐÐж¼½«·ÖÅÉÏàͬµÄ ROW_NUMBER¡£
RANK£º ¿ÉÒÔ·µ»ØÏàͬ»ò²î±ðµÄÅÅÃû£¬Ïêϸȡ¾öÓÚÐеÄÖµ¡£Í³Ò»ÅÅÃûϵÄËùÓÐÐн«·ÖÅÉÏàͬµÄ RANK¡£
ʹÓó¡¾°
ROW_NUMBER£º µ±ÐèÒª°´²åÈë˳Ðò¶ÔÐоÙÐбàºÅʱ£¬»òÕßÐèÒª¶Ô»ùÓÚÌض¨Ìõ¼þµÄÒ»Á¬×Ó¼¯¾ÙÐбàºÅʱ£¬ËüºÜÓÐÓá£
RANK£º µ±ÐèÒª¶ÔÐоÙÐÐÅÅÃûʱ£¬»òÕßÐèҪȷ¶¨¾ßÓÐÏàֵͬµÄÐеÄÏà¶ÔλÖÃʱ£¬ËüºÜÓÐÓá£
ʾÀý
-- ROW_NUMBER SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNum, * FROM table_name; -- RANK SELECT RANK() OVER (ORDER BY id) AS Rank, * FROM table_name;
µÇ¼ºó¸´ÖÆ
Ч¹û
id | RowNum | Rank |
---|---|---|
1 | 1 | 1 |
2 | 2 | 1 |
3 | 3 | 3 |
4 | 4 | 2 |
5 | 5 | 4 |
ÒÔÉϾÍÊÇsqlÖÐrownumberºÍrankÇø±ðµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡