简体   繁体   中英

MySQL selecting distinct values from a table, ordering by the count of rows with those distinct values

I'm currently working on a MySQL query, but I've been having a bit of trouble with it and am looking for help. I have been struggling with it for a while now and have searched for the solution from the Internet and from different coding forums, but, alas, still nothing.

Basically, I have a MySQL table as follows:

Table name: 'data'
'id' SMALLINT(5) auto_increment
'value_1' SMALLINT(5)
'value_2' SMALLINT(5)

The column 'value_2' has duplicate values and, so, I need to find the distinct values to process the results. So I created a MySQL query to do that.

SELECT DISTINCT value_1 FROM data WHERE value_2!="0"

The problem I'm having is that I want to order the results I just had by not the id nor by any other field, but by the number of rows that had those certain distinct values in that column ('value_1').

Could anyone please assist me?

What you'll need is GROUP BY and COUNT .

SELECT `value_1`, COUNT(`value_1`) AS `count` FROM `data` WHERE `value_2` != '0' GROUP BY `value_1` ORDER BY `count`;

For more information, see: http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html .

SELECT DISTINCT value_1, COUNT(*) FROM data GROUP BY value_1 ORDER BY 2 DESC;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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