Sql - 计算每个重复值的出现次数

时间:2017-01-22 15:17:08

标签: mysql sql

Here's my sample database

编辑:我想要的是对所有重复项的频率进行排名。我尝试使用之前建议的代码:

SELECT 
t.*,
@rn:=IF(@name = name,
    @rn + 1,
    IF(@name:=name, 1, 1)) freq
        FROM
(SELECT 
    *
FROM
    student
ORDER BY name) t
    CROSS JOIN
(SELECT @name:=NULL, @rn:=0) t2;

然而,这可以计算频率,但只有连续订购才能计算。见下图:

enter image description here

不是被算作3,而是将id 6下的数字1计算回1.

4 个答案:

答案 0 :(得分:1)

SELECT
    name, COUNT(*) 
FROM
    TableName 
GROUP BY
    name

此查询应该适合您。

答案 1 :(得分:1)

似乎你需要每次出现这个名字,所以一个简单的小组不会这样做。尝试这样的事情:

SELECT s.name AS "Name of Student",
       (SELECT COUNT(name) FROM student ss WHERE s.name = ss.name) AS "Frequency of Late"
  FROM student s

答案 2 :(得分:0)

这是您的解决方案

{{1}}

答案 3 :(得分:0)

使用用户变量:

Uri

编辑:

如果您想稍后按日期和频率订购,可以执行以下操作:

SELECT 
    t.*,
    @rn:=IF(@name = name,
        @rn + 1,
        IF(@name:=name, 1, 1)) freq
FROM
    (SELECT 
        *
    FROM
        student
    ORDER BY name) t
        CROSS JOIN
    (SELECT @name:=NULL, @rn:=0) t2;

编辑2:

有关更新的问题,请参阅以下内容:

select * from (
  /* the above query */
) t order by the_date_column desc, freq;

DEMO @ SQLFiddle