找出前n个平均值

时间:2012-09-10 13:47:00

标签: sql sql-server tsql

我有一个看起来像这样的表:

UID DATE GROUP VALUE

数据类型为:

 VARCHAR DATE VARCHAR NUMERIC

示例:

abc1000 2012-09-01 1205 1000.0000
abc1000 2012-09-01 1210 1010.0000
abc1000 2012-09-02 1205 1100.0000
abc1000 2012-09-02 1210 1020.0000
def1010 2012-09-01 1205 2000.0000

我需要为每个唯一的“UID + GROUP”找到前N(15)个值(VALUE)并平均它们,以便输出如下所示:

abc1000 1205 1050.0000
abc1000 1210 1015.0000
def1010 1205 2000.0000

2 个答案:

答案 0 :(得分:4)

select uid, [group], avg(value)
from
(
 select *,
        row_number() over (partition by uid, [group] order by value desc) rn 
        from yourtable
) v
where rn<=15
group by uid, [group]

答案 1 :(得分:0)

这是你在找什么?您需要使用AVG函数

SELECT TOP 15 [UID], [GROUP], AVG(VALUE) avgValue
FROM tableName
GROUP BY [UID], [GROUP]
ORDER BY avgValue DESC

或使用CTE

WITH cte AS
(
    SELECT [UID], [GROUP], AVG(VALUE) avgValue,
           ROW_NUMBER() OVER (Partition By AVG(VALUE) ORDER BY AVG(VALUE) DESC) as Row_Num
    FROM tableName
    GROUP BY [UID], [GROUP]
)
SELECT [UID], [GROUP], avgValue
FROM cte 
WHERE Row_Num <= 15

这将允许相同的总平均记录位于前15个列表中,例如

1 , rec 1, 100
2 , rec 2, 98
....
....
....
14, recX , 76
15, recY , 76
16, recZ , 76