嗨,我有这样的桌子:

 current | similar
   8     |2
   8     |4
   8     |4
   8     |4
   8     |4
   8     |5
   8     |5


但我想以这种方式首先使用4,因为它重复4次,重复5秒钟cuz重复两次,最后重复2次:

 current | similar
   8     |4
   8     |4
   8     |4
   8     |4
   8     |5
   8     |5
   8     |2


我尝试过:
select * from mytable order by similar,但我得到5的第一个,4秒的一个和最后的2

也:

select * from mytable order by count(similar) but only one row is returned


最后:
select *, count(similar) as a from mytable order by a,但是即使使用分组依据也不起作用,如何实现呢?谢谢

最佳答案

首先,您可以计算similar组中每个current字段的出现次数,然后使用原始表对join字段进行排序以对结果集进行排序。

select t1.current, t1.similar
from tbl t1
join (
    select current, similar, count(*) as ttl
    from tbl
    group by current, similar
) t2 on t1.current = t2.current and t1.similar = t2.similar
order by t1.current, t2.ttl desc


SQLFiddle

09-27 09:15