mysql - 如何增加 MySQL 中列值的出现次数

标签 mysql sql mysql-5.6

我有以下列名称:

  • customer_email
  • increment_id
  • other_id(假名)
  • created_at
  • increment_idother_id将是独一无二的,customer_email会有重复。返回结果时,我想知道电子​​邮件出现的次数。

    对于每一行,我想知道 customer_email 的次数是多少到目前为止,值(value)已经显现。会有order by条款结尾为created_at字段,我还计划添加一个 where 子句 where occurrences < 2
    我正在查询 > 500 万行,但性能并不是很重要,因为我将把它作为生产中只读副本数据库的报告运行。在我的用例中,我会为了健壮性而牺牲性能。
    | customer_email | incremenet_id | other_id | created_at          | occurances <- I want this |
    |----------------|---------------|----------|---------------------|---------------------------|
    | joe@test.com   | 1             | 81       | 2019-11-00 00:00:00 | 1                         |
    | sue@test.com   | 2             | 82       | 2019-11-00 00:01:00 | 1                         |
    | bill@test.com  | 3             | 83       | 2019-11-00 00:02:00 | 1                         |
    | joe@test.com   | 4             | 84       | 2019-11-00 00:03:00 | 2                         |
    | mike@test.com  | 5             | 85       | 2019-11-00 00:04:00 | 1                         |
    | sue@test.com   | 6             | 86       | 2019-11-00 00:05:00 | 2                         |
    | joe@test.com   | 7             | 87       | 2019-11-00 00:06:00 | 3                         |
    

    最佳答案

    您可以在早期版本的 MySQL 中使用变量:

    select t.*,
           (@rn := if(@ce = customer_email, @rn + 1,
                      if(@ce := customer_email, 1, 1)
                     )
           ) as occurrences
    from (select t.*
          from t
          order by customer_email, created_at
         ) t cross join
         (select @ce := '', @rn := 0) params;
    

    在 MySQL 8+ 中,我会推荐 row_number() :
    select t.*,
           row_number() over (partition by customer_email order by created_at) as occurrences
    from t;
    

    关于mysql - 如何增加 MySQL 中列值的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59180954/

    相关文章:

    php - 如何将一行的主键插入到它的另一列中?

    sql - 将外键绑定(bind)到非主键时有什么缺点吗?

    sql - 替换 MySQL 结果

    python - 如何在 Mysql Python 连接器中使用一个转义参数

    mysql - 使用 appsettings.json 文件时 Serilog.Sinks.MySQL 的配置

    SQL 查询 : Get average, 和所有高于某个值的平均值,在同一个查询中

    python - 如何向 MYSQL 插入多个值?

    mysql - 删除 MySQL 中的范围

    Mysql查询结果为每个类别生成月份(1-12)并按类别按同一列顺序排列

    Mysql 5.6 UTF-8 (utf8mb4) 仍然显示不正确的字符