Get n grouped categories and sum others into one

前端 未结 3 778
别跟我提以往
别跟我提以往 2020-12-21 03:57

I have a table with the following structure:

Contents (
  id
  name
  desc
  tdate
  categoryid
  ...
)
         


        
3条回答
  •  渐次进展
    2020-12-21 04:46

    You can approach this with nested aggregation. The inner aggregation calculates the counts along with a sequential number. You want to take everything whose number is 7 or less and then combine everything else into the others category:

    SELECT (case when seqnum <= 7 then label else 'others' end) as label,
           (case when seqnum <= 7 then catid end) as catid, sum(cnt)
    FROM (SELECT ca.name AS label, ca.id AS catid, COUNT(c.id) AS cnt,
                 row_number() over (partition by ca.name, catid order by count(c.id) desc) as seqnum
          FROM contents c LEFT OUTER JOIN
               category ca
               ON ca.id = c.categoryid
          GROUP BY label, catid
         ) t
    GROUP BY (case when seqnum <= 7 then label else 'others' end),
             (case when seqnum <= 7 then catid end) 
    ORDER BY cnt DESC ;
    

提交回复
热议问题