Consulta de SQL Server para Rango (Número de fila) y Agrupaciones
Tengo una tabla que tiene algunas columnas: User, Category, Value
Y quiero hacer una consulta que me dará un ranking, de todos los usuarios por el valor, pero restablecer para la categoría.
Ejemplo:
user1 CategoryA 10
user2 CategoryA 11
user3 CategoryA 9
user4 CategoryB 3
user1 CategoryB 11
La consulta devolvería:
Rank User Category
1 user2 CategoryA
2 user1 CategoryA
3 user3 CategoryA
1 user1 CategoryB
2 user4 CategoryB
¿Alguna idea?
Escribo la consulta y especifique la Categoría, funciona pero luego tengo que escribir bucles y es muy lento.
22
2 answers
Use "Partition by" en la función de clasificación SOBRE la cláusula
SELECT
Rank() over (Partition by Category Order by Value, User, Category) as ranks,
Category, User
FROM
Table1
Group By
User, Category, Value
Order by
ranks asc
44
Author: gbn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-16 19:24:19
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-16 19:24:19
Select User, Category,
(Select Count(*) From Table
Where Category = A.Category
And Value <= A.Value) Rank
From Table A
Order By Category, Value
Si Value puede tener duplicados, entonces debe decidir si desea 'contar' los duplicados (equivilent to RANK) o no (equivilent to DENSE_RANK, thanx @shannon)
Rango ordinario:
Select User, Category,
(Select 1 + Count(*) From Table -- "1 +" gives 1-based rank,
Where Category = A.Category -- take it out to get 0-based rank
And Value < A.Value) Rank
From Table A
Order By Category, Value
Rango"denso":
Select User, Category,
(Select 1 + Count(Distinct Value) -- "1 +" gives 1-based rank,
From Table -- take it out to get 0-based rank
Where Category = A.Category
And Value < A.Value) Rank
From Table A
Order By Category, Value
3
Author: Charles Bretana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-17 03:03:51
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-17 03:03:51