在SQL列中查找最常用的值
我怎样才能findSQL表中给定列中最频繁的值?
例如,对于这个表,它应该返回two
因为它是最常见的值:
one two two three
SELECT `value`, COUNT(`value`) AS `value_occurrence` FROM `my_table` GROUP BY `value` ORDER BY `value_occurrence` DESC LIMIT 1;
尝试像这样:
SELECT `column` FROM `your_table` GROUP BY `column` ORDER BY COUNT(*) DESC LIMIT 1;
让我们把表名称作为city
tblperson
和列名。 我想从城市列中找回最重复的城市:
select city,count(*) as nor from tblperson group by city having count(*) =(select max(nor) from (select city,count(*) as nor from tblperson group by city) tblperson)
这里nor
是一个别名。
下面的查询似乎在SQL Server数据库中对我有用:
select column, COUNT(column) AS MOST_FREQUENT from TABLE_NAME GROUP BY column ORDER BY COUNT(column) DESC
结果:
column MOST_FREQUENT item1 highest count item2 second highest item3 third higest .. ..
用于SQL Server。
由于没有限制命令的支持。
哟可以使用top 1命令来查找在这种情况下特定列中的最大值(值)
SELECT top1 `value`, COUNT(`value`) AS `value_occurrence` FROM `my_table` GROUP BY `value` ORDER BY `value_occurrence` DESC;
假设表格是' SalesLT.Customer
',你试图找出的列是' CompanyName
',而AggCompanyName
是一个别名。
Select CompanyName, Count(CompanyName) as AggCompanyName from SalesLT.Customer group by CompanyName Order By Count(CompanyName) Desc;
如果您不能使用LIMIT或LIMIT不是您的查询工具的选项。 你可以使用“ROWNUM”来代替,但是你需要一个子查询:
SELECT FIELD_1, ALIAS1 FROM(SELECT FIELD_1, COUNT(FIELD_1) ALIAS1 FROM TABLENAME GROUP BY FIELD_1 ORDER BY COUNT(FIELD_1) DESC) WHERE ROWNUM = 1