Funções de Ranqueamento
Autor: Wesley Leal | Publicado: 2012-10-23T03:38:00-07:00

  Existem 4 funções de ranqueamento que podem ser utilizados com a cláusula OVER:    ROW_NUMBERRANKDENSE_RANKNTILE  Um exemplo de uso:  SELECT orderid, custid, val,  &nbsp; ROW_NUMBER() OVER(ORDER BY val) AS rownum,  &nbsp; RANK()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; OVER(ORDER BY val) AS rank,  &nbsp; DENSE_RANK() OVER(ORDER BY val) AS dense_rank,  &nbsp; NTILE(10)&nbsp;&nbsp; OVER(ORDER BY val) AS ntile  FROM Sales.OrderValues  ORDER BY val;  O retorno é:  orderid&nbsp;&nbsp;&nbsp;&nbsp; custid&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; val&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; rownum&nbsp; rank&nbsp;&nbsp;&nbsp; dense_rank ntile  ----------- ----------- --------- ------- ------- ---------- -----  10782&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 12&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 12.50&nbsp;&nbsp;&nbsp;&nbsp; 1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1  10807&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 27&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 18.40&nbsp;&nbsp;&nbsp;&nbsp; 2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1  10586&nbsp;&nbs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ER() retorna uma ordenação sequencial para o resultado da consulta, baseado no que foi especificado no ORDER BY da cláusula OVER. Note que eu poderia retornar a ordenação pela coluna custid, modificando apenas a coluna rownum e mantendo   a mesma ordem no retorno da consulta.  Ao contrário da função ROW_NUMBER(), onde cada registro obrigatoriamente possuirá um valor distinto (inclusive desconsiderando os empates - veja as linhas 7 e 8), as funções RANK e DENSE_RANK levam os empates em consideração. A diferença entre elas diz respeito   ao próximo registro. Enquanto a função RANK considera a quantidade de linhas para determinar o próximo registro (dois empates com valor 7 e o próximo registro com valor 9), a função DENSE_RANK leva em consideração os registros distintos (mesmo estando na linha   9, o empate nos dois registros anteriores produziu como retorno o valor 8).  A função NTILE faz com que o retorno seja agrupado em quantidades iguais (ou a mais próxima possível). Como a consulta possui 830 registros e foi solicitado dividir em 10 grupos, o SQL SERVER dividiu em 10 grupos iguais de 83 registros cada. Se o retorno   fosse, por exemplo, de 832 registros, ele incluiria 1 registro a mais nos 2 primeiros grupos, ou seja, o primeiro e o segundo bloco teriam 84 registros, enquanto os demais teriam 83 registros cada.          Confidencialidade: A informação contida nesta mensagem de e-mail, incluindo quaisquer anexos, é confidencial e está reservada apenas à pessoa ou entidade para a qual foi endereçada. Se você não é o destinatário ou a pessoa responsável por encaminhar esta mensagem   ao destinatário, você está, por meio desta, notificado que não deverá rever, retransmitir, imprimir, copiar, usar ou distribuir esta mensagem de e-mail ou quaisquer anexos. Caso você tenha recebido esta mensagem por engano, por favor, contate o remetente imediatamente   e apague esta mensagem de seu computador ou de qualquer outro banco de dados. Muito obrigado.  Confidentiality Notice: The information contained in this email message, including any attachment, is confidential and is intended only for the person or entity to which it is addressed. If you are neither the intended recipient nor the employee or agent responsible   for delivering this message to the intended recipient, you are hereby notified that you may not review, retransmit, convert to hard copy, copy, use or distribute this email message or any attachments to it. If you have received this email in error, please   contact the sender immediately and delete this message from any computer or other data bank. Thank you.