gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:53:05 24 4
gpt4 key购买 nike

我有以下列名称:

  • 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com