简体   繁体   English

在SQL中使用ORDER BY子句

[英]Using the ORDER BY clause in SQL

Is it possible to use a keyword that would order the results in my SELECT QUERY by the number of times they appear in the data table? 是否可以使用一个关键字来按结果出现在数据表中的次数对我的SELECT QUERY中的结果进行排序?

MySQL: MySQL:

  SELECT * FROM interests ORDER BY (keyword)

The table values: 该表的值:

hiking
running
swimming
hiking
photography
swimming
hiking

If the Order in which they are returned is based on the frequency of each values occurence in the table it would be: 如果返回它们的顺序基于表中每个值出现的频率,则为:

hiking
hiking
hiking
swimming
swimming
running
photography

If there is no one particular keyword, how can I achieve this with SQL? 如果没有一个特定的关键字,如何使用SQL来实现呢?

Thanks 谢谢

SELECT COUNT(keyword) AS cnt, keyword
FROM interested
GROUP BY keyword
ORDER BY cnt

would give you the count of each keyword in ascending order. 会给您每个关键字的升序排列。 But you wouldn't get 3 hiking entries, 2swimming, etc... just hiking,3 , swimming,2 , etc... 但是您不会获得3个远足项目swimming,2项目等...仅hiking,3swimming,2等...

SELECT  a.*
FROM    interests a
        INNER JOIN 
        (
            SELECT  keyword, COUNT(*) totalCount
            FROm    interests
            GROUP BY keyword
        ) b ON a.keyword = b.keyword
ORDER   BY b.totalCount DESC
    SELECT 
    t1.*,count(t1.keyword) 
    FROM 
    interests AS t1 INNER JOIN (
     SELECT 
            keyword,count(*) totalcount 
      FROM 
            interests GROUP BY keyword
      )t2 
ON t1.keyword=t2.keyword group by t1.keyword 
   ORDER BY t2.totalcount DESC

Sql Fiddle demo SQL Fiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM