SQL - 获取按出现次数排序的数据数组

时间:2011-01-27 20:10:07

标签: sql database arrays

我的列中有一个包含此类数据的表:

ANS1228E
ANS4987E
ANS1228E
ANS4987E
ANS1228E
ANS4987E
ANS1228E
ANS4987E
ANS1228E
ANS4987E
ANS1802E
ANS1228E
ANS5258E
ANS1375E
ANS1999E
ANS5258E
ANS1228E
ANS5258E
ANS1375E

我想接受这些条目并使用按其出现次数排序的唯一条目创建一个数组。

要使用的SQL命令是什么。

我想得到这个结果:

Code            Occurrences
------          ----------
ANS1228E                67
ANS4987E                57
ANS1017E                51
ANS1948E                 8
ANS5258E                 7
ANS1802E                 7
ANS4007E                 3
ANS1375E                 3
ANS1301E                 2
ANS5279E                 2
ANS5280E                 2
ANS1468E                 1
ANS1487E                 1

解决方案:(感谢Chris B. Behrens)

SELECT code, COUNT(code) FROM table GROUP BY code ORDER BY COUNT(code) DESC

5 个答案:

答案 0 :(得分:3)

尝试一下:

SELECT code, COUNT(Code) FROM TABLE GROUP BY Code ORDER BY COUNT(Code) desc

除此之外,我们需要知道您正在尝试创建阵列的平台。

答案 1 :(得分:2)

select column_name, count(*)
from table
group by column_name
order by count(*) desc

编辑:添加了排序顺序desc

答案 2 :(得分:0)

SQL很简单:

select theValue
     , count(*)
  from theTable
 group by theValue
 order by count(*) desc

在应用程序中将其作为数组获取意味着您传递sql并检索行,大多数语言都支持将此数据作为数组返回。

答案 3 :(得分:0)

首先,您需要使用SQL语句来获取列表并计算

select yourcolumnname, count(*) as numberofoccurences
from yourtable
group by yourcolumnname
order by numberofoccurences desc

下一部分将在很大程度上取决于您使用的工具,但通常,您将使用此SQL创建查询,然后检索行,并为每行将元素(value,numberofoccurences)推送到数组中。 / p>

答案 4 :(得分:0)

您正在寻找group by条款。按列分组时,您可以计算聚合,包括COUNT。然后,您可以按该计数订购结果集,并获得您想要的结果。