2009-04-27 24 views
0

这是指我之前问过的问题,并且得到了一个非常快速的答案(max count together in an sql query)。该问题类似,但前提问题中的解决方案会迫使我在循环中访问数据库,这会导致性能问题。所以现在我有一些加入后:在SQL查询中一起计算最大值2

id | description 
    0 | bla 
    0 | blub 
    0 | bla 
    1 | blablub 
    1 | bla 
    ... | ... 

正如你可以看到,现在的id不是主键了。我想要的是获得结果集中每个id最常用的描述。它应该看起来像这样:

id | most_popular_description | times_the_desc_appeared_for_an_id 
    0 |      bla |         2 
    1 |     blablub |         1 
... |      ... |        ... 

回答

1

如果你只想要最流行的项目,那么我相信这应该会给你你要找的结果集。还有其他方法可以做到这一点,但stats_mode是获得组中“最流行”值最简单的方法(即模式)。

SELECT t.id, 
     t.description AS most_popular_description, 
     COUNT(*) AS times_the_desc_appeared_for_an_id 
FROM mytable t INNER JOIN (
    SELECT id, stats_mode(description) AS desc FROM mytable GROUP BY id 
) a ON t.id = a.id AND t.description = a.desc 
GROUP BY t.id, t.description; 

请注意,嵌套查询(内联视图)是必要的,因为您还需要计数。

+0

非常酷,非常感谢 – Red33mer 2009-05-01 05:37:12

1

这应该有所斩断。

select id, description, COUNT(description) 
from mytable 
group by id, description 
order by 3 desc 
+0

SRY基因,但它并不完全是我想要的,还是感谢帮助 – Red33mer 2009-05-01 05:36:53

0

我想你可以使用dense_rank()分析函数来获取每个组集的前N个。

事情是这样的:

select id, description, times_the_desc_appeared_for_an_id 
from 
(
    select id, description, count(description) times_the_desc_appeared_for_an_id 
    dense_rank() over (partition by id, description order by count(description) desc) position 
    from mytable 
    group by id, description 
) 
where 
    position <= 3 
order by id, times_the_desc_appeared_for_an_id; 
+0

还没有测试它,因为通过rwwilden工程解决方案,但还是谢谢你 – Red33mer 2009-05-12 20:30:21