Mostrar el valor de la mediana de una tabla dinámica [duplicado]

Posible duplicado:
Función para calcular la mediana en Sql Server

Meta:
Display the value of the median based on this code below.

Problema:
I don't how to do display it in SQL server

The table can retrieve new value in the future and all rows can be odd or even.

declare @T table 
( 
  Name varchar(50), 
  Sales int 
) 

insert into @T values 
('John',     '50'), 
('Jennifer', '15'), 
('Stella',   '20'), 
('Sophia',   '40'), 
('Greg',     '10'), 
('Jeff',     '20')

preguntado el 09 de marzo de 12 a las 16:03

1 Respuestas

Esto debería funcionar:

SELECT AVG(tt.Sales) AS Median 
FROM (
    SELECT TOP 1 t1.* FROM 
    (SELECT TOP 50 PERCENT FROM @T ORDER BY Sales) t1
    ORDER BY t1.Sales DESC
    UNION
    SELECT TOP 1 t2.* FROM 
    (SELECT TOP 50 PERCENT FROM @T ORDER BY Sales  DESC) t2
    ORDER BY t2.Sales
) tt

To just display it, you can do

DECLARE @Median REAL
SELECT @Median=AVG(tt.Sales) AS Median 
FROM (
    SELECT TOP 1 t1.* FROM 
    (SELECT TOP 50 PERCENT FROM @T ORDER BY Sales) t1
    ORDER BY t1.Sales DESC
    UNION
    SELECT TOP 1 t2.* FROM 
    (SELECT TOP 50 PERCENT FROM @T ORDER BY Sales  DESC) t2
    ORDER BY t2.Sales
) tt

PRINT CONVERT(VARCHAR, @Median)

respondido 09 mar '12, 16:03

Please don't use VARCHAR without specifying length. sqlblog.com/blogs/aaron_bertrand/archive/2009/10/09/… - Aarón Bertrand

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.