1

I have a table t1 with two int fields(id,month) and I have populated it with some values. What I would like to see as an output is, the maximum of (count of id in a month). I have tried the following code and it works fine:

select id,max(freq) as maxfreq from 
(select id,month,count(*) as freq
from t1
group by id,month) a
group by id
order by maxfreq desc

The result is:

ID  MAXFREQ
1   3
2   3
3   1
4   1

This is fine. How to achieve this using the over partition by clause? And which one is more efficient? In reality my table consists of several thousands of records. So doing a subquery wont be a good idea I guess! Thanks for any help. Here's the fiddle

4

3 回答 3

0
;WITH tmp AS (select id, row_number() over (partition by id, month order by id) rn
         FROM t1)
SELECT t.id, max(tmp.rn) as maxfreq
from t1 t
INNER JOIN tmp ON tmp.id = t.id
GROUP BY t.id
于 2014-09-12T07:31:18.810 回答
0

相同的解决方案,但使用 CTE。实际上,在这个问题上强行使用窗口函数是没有意义的。将两种解决方案与计划浏览器进行比较。

; with c1 as ( select id,month,count(*) as freq from t1 group by id,month ) select id, max(freq) as maxfreq from c1 group by id order by maxfreq desc;

于 2014-09-12T09:50:48.290 回答
0

你可以试试这个——

select id,max(freq) as maxfreq from 
(select id,row_number() over (partition by id,month ORDER BY id) as freq
from t1
) a
group by id
order by id,maxfreq desc

但从性能的角度来看,我认为您的原始查询和这个查询之间没有太大区别。

于 2014-09-12T07:35:59.530 回答