我有一列,我只想返回不匹配某些条件的不同值,按最常见值的降序排列。
该列包含以下记录:
this
those
that
dog
these
here
there
cat
dog
hamster
hamster
there
blah
here
blah
blah
dog
所以我有:
SELECT DISTINCT(rcolumn)
FROM otable
WHERE reason != 'this'
AND reason != 'that'
AND reason != 'those'
AND reason != 'these'
AND reason != 'them'
AND reason != 'here'
AND reason != 'there'
AND reason != 'in between'
AND reason != 'all over'
AND reason != 'something'
AND reason != 'something else'
AND reason != 'anywhere'
AND reason != 'anywhere else'
将返回:
blah
cats
hamsters
dogs
但我希望它返回:
blah
dogs
hamsters
cats
按照这个顺序,表中出现最多的是“blah”,然后是狗,然后是仓鼠,然后是猫。
最佳答案
为了按频率顺序返回内容,您需要对值进行GROUP BY
:
SELECT rcolumn
FROM otable
-- WHERE stuff
GROUP BY rcolumn;
这应该给出与您得到的答案基本相同的答案。然后您可以轻松计算每行的发生率并排序:
SELECT rcolumn, COUNT(*) AS frequency
FROM otable
GROUP BY rcolumn
ORDER BY frequency DESC;
如果您不想在结果中看到计算出的频率列,那么您可以直接按此订购:
SELECT rcolumn
FROM otable
GROUP BY rcolumn
ORDER BY COUNT(*) DESC;
一般来说,在使用 GROUP BY
子句时,请小心仅选择:
- 分组依据的列
- 聚合函数的结果
大多数 RDBMS 都会将此视为错误,但 MySQL 只会选择随机行并返回该数据。
最后,为了更加清晰,为什么不将长 WHERE
子句更改为更优雅的内容:
WHERE rcolumn NOT IN
('this'
,'that'
,'those'
-- ...
)
关于mysql - 按频率顺序选择最常出现的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24655764/