目标:
根据以下代码显示中值的值。
问题:
我不知道如何在SQL server中显示它
该表可以在将来检索新值,并且所有行都可以是奇数或偶数。
declare @T table
(
Name varchar(50),
Sales int
)
insert into @T values
('John', '50'),
('Jennifer', '15'),
('Stella', '20'),
('Sophia', '40'),
('Greg', '10'),
('Jeff', '20')
答案 0 :(得分:0)
这应该有效:
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
要显示它,你可以
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)