mysql - 如何在 MySQL 中增加列值的出现次数
问题描述
我有以下列名称:
- 客户电子邮件
- 增量ID
- other_id(假名)
- created_at
increment_id
并且other_id
将是唯一的,customer_email
将有重复。当结果返回时,我想知道电子邮件的出现次数。
对于每一行,我想知道到目前为止customer_email
该值出现了多少次。该字段的末尾会有一个子句,我还计划添加一个 where 子句order by
created_at
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;
在 MyQL 8+ 中,我建议row_number()
:
select t.*,
row_number() over (partition by customer_email order by created_at) as occurrences
from t;
推荐阅读
- typescript - 打字稿 - 数组的键值
- powershell-5.0 - 有没有办法用打字机效果输出运行 powershell 脚本?
- xcode - 升级到 macOS Catalina 后,运行 XCUITest 将不断出现“正在验证“AAA”...”弹出窗口
- c++ - 缓存 std::array 的选定元素并在 C++ 中自动保持一致
- c - 在 C 中运行用户定义的函数时出现“与局部变量相关的堆栈内存地址”错误
- python - matplotlib:在每条迹线与右侧 y 轴相交的地方放置图例标签
- android - 原生 *.so 库及其标头在 android 项目中的位置?
- javascript - 按日期顺序对nodejs中的数组进行排序(从最近到最旧)
- linux - 使用 HUGETBL 映射文件的 Linux 内存
- c - 为什么在 C 中的这个 realloc 命令之后 valgrind 输出无效读取?