简体   繁体   English

一个SQL查询中最大计数一起2

[英]max count together in an sql query 2

This is referring to the question i asked before, and got a really quick answaer ( max count together in an sql query ). 这是指我之前问过的问题,并且得到了非常快的回答( 在sql查询中最大和在一起 )。 The Problemset is similar, but the solution in the prevous question would force me to access a db in a loop which will cause performance problems. 问题集是相似的,但是上一个问题中的解决方案迫使我循环访问数据库,这将导致性能问题。 So what i have now, after some joins is: 因此,经过一些加入,我现在拥有的是:

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

As u can see, now the id is not a primary key anymore. 如您所见,现在id不再是主键。 What i want is to get the most used description for each id in the resultset. 我想要的是获取结果集中每个ID的最常用的描述。 It should look something like this: 它看起来应该像这样:

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

This should do the trick. 这应该可以解决问题。

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

If you only want the most popular items, then I believe this should give you the result set you're looking for. 如果您只想要最受欢迎的商品,那么我相信这应该会为您提供想要的结果集。 There are other ways of doing this, but stats_mode is the easiest way to obtain the "most prevalent" value in a group (ie the Mode). 还有其他方法可以执行此操作,但是stats_mode是获取组中“最普遍”值(即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;

Note that the nested query (inline view) is necessary since you also want the count. 请注意,嵌套查询(内联视图)是必需的,因为您还需要计数。

I think you can use the dense_rank() analytic function to get the top N for each group set. 我认为您可以使用density_rank()分析函数来获取每个组的前N个。

Something like this: 像这样:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM