2

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

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
4

2 回答 2

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]
于 2012-09-10T13:51:14.990 回答
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
于 2012-09-10T13:51:23.587 回答