2012-09-10 338 views
2

我有一個表,看起來像這樣:查找前n平均值

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
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] 
+0

我想就是這個!請允許我表達我的謝意......我昨天花了8個小時沒有結果,我非常感激!謝謝! –

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 
+0

謝謝你的回答,我相信其他答案就是我要找的。 –