如何在sql中打印唯一的元素并计算频率?

qrjkbowd  于 2021-06-15  发布在  Mysql
关注(0)|答案(5)|浏览(329)

我有一张这样的table,

Name  ActionCategory
Ana    1
Joe    2
Bob    1
Tom    3
Joe    4
Ana    5
...

我想写一个sql,可以找到唯一的名称和计数的数目出现。预期输出如下:

Name     Appearance
Ana      2
Joe      2
Bob      1
Tom      1

我能用下面的sql打印出唯一的名字,有人能告诉我如何计算外观吗?

SELECT 
   DISTINCT(Name) as UniqueNames
FROM
   tableName

谢谢

wsxa1bj1

wsxa1bj11#

您可以通过简单地运行以下查询来实现这一点

SELECT 
      Name as UniqueNames, count(Name) as occurrences
FROM
      tableName
HAVING occurrences > 0 --you may ignore this condition
GROUP BY Name
ORDER BY UniqueNames
rsl1atfo

rsl1atfo2#

你可以用 group by ```
SELECT Name , count(Name) as Appearance
FROM yourtable
GROUP BY NAME

sczxawaw

sczxawaw3#

您将需要使用distinct和group by来获得外观数,如下所示:

SELECT distinct(Name), count(Name) as 'Appearance' from test_table group by Name;
omvjsjqw

omvjsjqw4#

您可以在下面尝试使用聚合函数count()并应用group by

SELECT 
   Name,count(Name) as UniqueNames
FROM
   tableName
group by Name
ioekq8ef

ioekq8ef5#

您可以使用:

SELECT 
   Name, count(Name) as TotalAppearance
FROM
   tableName
group by Name
having count(Name) > 0
order by TotalAppearance desc;

您也可以使用order by。

相关问题