如何根据点击次数订购值

时间:2017-01-17 08:44:17

标签: mysql sql sorting sql-order-by

我想按从大多数到最小的顺序检索表值。例如,如果我们有一个像下面这样的列表,

 selected_val
    2
    3
    3
    2
    1
    3
    1
    1
    1
    4

我需要一个SQL,它将以1,3,2,4的顺序返回值,因为表中有四个1,三个3,两个2和一个4。我想要1,1,1,1,3,3,3,2,2,4。这可能吗?

如果我添加了更多的colums

selected_val   Rack
    2           A
    3           A
    3           B
    2           B
    1           C
    3           C
    1           A
    1           A
    1           B
    4           C

感谢您的帮助

4 个答案:

答案 0 :(得分:3)

您可以使用计数和分组

 select selected_val
 from my_table 
 group by selected_val
 order by count(*) DESC

对于问题的第二部分,如果您需要与selected_vale相关的机架,则可以使用group concat

 select selected_val, group_concat(rack)
 from my_table 
 group by selected_val
 order by count(*) DESC

或者如果您需要相对计数和订单

,请将列架添加到分组依据
 select selected_val, rack
 from my_table 
 group by selected_val, rack
 order by count(*) DESC

答案 1 :(得分:1)

尝试使用所需的输出,您也可以选择其他列:

select t.selected_val 
from test t
inner join (
            select t1.selected_val, count(1) ord
            from test t1
            group by t1.selected_val) t2 on t2.selected_val = t.selected_val
order by t2.ord desc

<强>输出: 1 1 1 1 3 3 3 2 2 4

输出实际上不在行中,但您可以使用GROUP_CONCAT来检索行中的输出。

答案 2 :(得分:0)

使用子查询进行计数,然后将LEFT JOIN结果计数到子查询的结果和按顺序排序。

select t1.selected_val from table t1
  left join (
        SELECT
          t2.selected_val,
          count(*) AS count
        FROM table t2
        GROUP BY selected_val
    ) t3 on t1.selected_val = t3.selected_val
ORDER BY t3.count DESC;

答案 3 :(得分:0)

使用交叉连接。

          select A.C,A.Rack from  
           (select selected_val,Rack,count(*) c from #TableName group by selected_val,Rack)a
          ,(select selected_val,Rack,count(*) c from #TableName group by selected_val,Rack)b
          where B.c <= A.selected_val
          ORDER BY A.selected_val DESC
  

OutPut:

enter image description here