按重要性排序,然后按部分分组

时间:2019-03-24 15:03:58

标签: mysql sql greatest-n-per-group

在此表方案http://sqlfiddle.com/#!9/101a9c/9/0

id  section     rev     importance
2   1           b       6
1   1           a       5
3   2           c       9
5   3           e       6
4   3           d       5

我想先order by **importance**然后group by **section**

所以我尝试使用GROUP BY docs.section

SELECT docs.id, docs.section, docs.rev, (
  SELECT SUM(docs_importance.importance) 
  FROM docs_importance
  WHERE docs_importance.doc_id = docs.id
) AS importance
FROM docs
GROUP BY docs.section    ---GROUPING
ORDER BY docs.section, importance DESC

但是得到了这个结果:

id  section     rev     importance
1   1           a       5
3   2           c       9
4   3           d       5

但是我想要的结果应该是

id  section     rev     importance
2   1           b       6
3   2           c       9
5   3           e       6

2 个答案:

答案 0 :(得分:0)

这适用于更高版本的MySql:

with 
  grp as (
    select d.section, d.id, sum(i.importance) imp
    from docs d inner join docs_importance i
    on i.doc_id = d.id  
    group by d.section, d.id  
  ),
  cte as (
    select grp.id, grp.section, grp.imp
    from grp inner join (
      select section, max(imp) maximp
      from grp
      group by section
    ) t on t.section = grp.section and t.maximp = grp.imp 
  )
select d.id, d.section, d.rev, cte.imp importance 
from docs d inner join cte
on cte.id = d.id and cte.section = d.section

请参见demo
结果:

| id  | section | rev | importance |
| --- | ------- | --- | ---------- |
| 2   | 1       | b   | 6          |
| 3   | 2       | c   | 9          |
| 5   | 3       | e   | 6          |

对于旧版本:

select d.id, d.section, d.rev, cte.imp importance 
from docs d inner join (
    select grp.id, grp.section, grp.imp
    from (
    select d.section, d.id, sum(i.importance) imp
    from docs d inner join docs_importance i
    on i.doc_id = d.id  
    group by d.section, d.id  
  ) grp inner join (
      select section, max(imp) maximp
      from (
    select d.section, d.id, sum(i.importance) imp
    from docs d inner join docs_importance i
    on i.doc_id = d.id  
    group by d.section, d.id  
  )grp 
  group by section
    ) t on t.section = grp.section and t.maximp = grp.imp 
  )cte
on cte.id = d.id and cte.section = d.section

请参见demo

答案 1 :(得分:0)

我使用了此查询

SELECT t.id, t.section, t.rev, t.importance FROM (
   SELECT docs.id, docs.section, docs.rev, (SELECT SUM(docs_importance.importance) FROM docs_importance WHERE docs_importance.doc_id = docs.id) AS importance
   FROM docs
   GROUP BY docs.id
   ORDER BY importance DESC
) AS t
GROUP BY t.section

我首先在其中做一个子查询作为临时表,然后按重要性对其进行排序,然后按部分对外部查询进行分组以获得最终结果。