簡體   English   中英

一個SQL查詢中最大計數一起2

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM