[英]max count together in an sql query 2
这是指我之前问过的问题,并且得到了非常快的回答( 在sql查询中最大和在一起 )。 问题集是相似的,但是上一个问题中的解决方案迫使我循环访问数据库,这将导致性能问题。 因此,经过一些加入,我现在拥有的是:
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
... | ... | ...
这应该可以解决问题。
select id, description, COUNT(description)
from mytable
group by id, description
order by 3 desc
如果您只想要最受欢迎的商品,那么我相信这应该会为您提供想要的结果集。 还有其他方法可以执行此操作,但是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;
请注意,嵌套查询(内联视图)是必需的,因为您还需要计数。
我认为您可以使用density_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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.