日期:2014-05-18  浏览次数:20490 次

sqlserver有没有取一个字段的中位数的函数?
sqlserver有没有取一个字段的中位数的函数?

------解决方案--------------------
SQL code
CREATE  TABLE tsgss(id varchar(20),a int)
INSERT tsgss SELECT '0001',1
UNION ALL SELECT '0002',3
UNION ALL SELECT '0003',66
UNION ALL SELECT '0004',34
UNION ALL SELECT '0005',6
UNION ALL SELECT '0006',45
UNION ALL SELECT '0007',23
UNION ALL SELECT '0008',33
UNION ALL SELECT '0009',7
UNION ALL SELECT '0010',9
go
CREATE   FUNCTION getMid()
RETURNS float
AS
BEGIN
    DECLARE @s table(id int identity(1,1),a int)
    DECLARE @g float
    
    INSERT @s SELECT a FROM tsgss
    IF @@ROWCOUNT %2<>0 
        SELECT @g=a FROM @s WHERE id=(SELECT min(id)+max(id) FROM @s)/2
    ELSE
        SELECT @g=avg(a*1.0) FROM @s WHERE id in(SELECT max(id)/2 FROM @s UNION ALL SELECT max(id)/2+1 FROM @s)
    RETURN @g
END
SELECT dbo.getMid()