sql 2008得到max,min,avg,Stdev,median

时间:2014-06-13 18:43:53

标签: sql sql-server reporting-services

我一直致力于ssrs报道,我的任务是获得Fish Max,Min,Avg,Stdev,Medain的长度和重量来自Catches by group by speciesId,我能够得到Max,Min,Avg of每个物种的长度和重量但是棘手的部分是获得长度和重量的中位数,我一直在google寻找解决方案并找到不同的解决方案,但我不确定哪一个适合我的情况。这是我的临时表

我使用的是SQL 2008

CREATE TABLE #Catchestemp
(
id int, -- Primary key
speciesID int, --foreign key
catchWeight numeric(6,2),
catchLength numeric(6,3)

)

INSERT INTO #Catchestemp (id, speciesID,catchWeight,catchLength)
VALUES 
(1,1,500.00,16.000),
(2,1,160.00,25.000),
(3,2,36.00,13.000),
(4,2,15.00,20.000),
(5,3,25.00,25.000),
(6,3,24.00,128.000),
(7,4,26.00,163.000),
(8,5,24.00,172.000),
(9,5,27.00,172.000),
(10,6,27.00,172.000),
(11,6,25.00,158.000),
(12,6,26.00,134.000),
(13,6,28.00,154.000),
(14,1,240.00,133.000),
(15,1,100.00,114.000),
(16,1,90.00,216.000),
(17,1,50.00,168.000),
(18,7,24.00,115.000),
(19,7,25.00,104.000),
(20,7,27.00,136.000),
(21,7,19.00,74.000),
(22,3,19.00,64.000),
(23,1,50.00,147.000),
(24,1,69.00,146.000),
(25,1,80.00,106.000)

SELECT * from  #Catchestemp
DROP table #Catchestemp

请帮我解决这个问题,我将非常感谢所有答案 先感谢您。

1 个答案:

答案 0 :(得分:0)

此查询应该这样做。使用Function to Calculate Median in Sql Server

中的解决方案

只需从#Catchestemp"替换你的" SELECT *用这个查询。

select a.*,b.MedianWeight,c.MedianLength from (
    SELECT speciesID, min(catchLength) MinLength, max(catchLength) MaxLength, avg(catchLength) AvegrageLength, isnull(STDEV(catchLength),0) StDevLength
    , min(catchWeight) MinWeight, max(catchWeight) MaxWeight, avg(catchWeight) AvegrageWeight, isnull(STDEV(catchWeight),0) StDevWeight
    from  #Catchestemp c
    group by speciesID
) a
join (
    select speciesID, avg(catchWeight) MedianWeight from (
        select speciesID,
            catchWeight,
            ROW_NUMBER() OVER (PARTITION BY speciesID ORDER BY catchWeight ASC, id ASC) AS RowAsc,
            ROW_NUMBER() OVER (PARTITION BY speciesID ORDER BY catchWeight DESC, id DESC) AS RowDesc
        from #Catchestemp
    ) x
    WHERE RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)
    group by speciesID
) b on a.speciesID = b.speciesID
join (
    select speciesID, avg(catchLength) MedianLength from (
        select speciesID,
            catchLength,
            ROW_NUMBER() OVER (PARTITION BY speciesID ORDER BY catchLength ASC, id ASC) AS RowAsc,
            ROW_NUMBER() OVER (PARTITION BY speciesID ORDER BY catchLength DESC, id DESC) AS RowDesc
        from #Catchestemp
    ) x
    WHERE RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)
    group by speciesID
) c on a.speciesID = c.speciesID