mysql - 相对于 SQL 中另一列中的值创建一个新的增量列
问题描述
假设我有一张桌子
CustomerID Country
1 Germany
6 Germany
17 Germany
25 Germany
32 USA
36 USA
39 Germany
43 USA
44 Germany
我想创建一个新的专栏来说明与国家相关的外观
CustomerID Country Count
1 Germany 1
6 Germany 2
17 Germany 3
25 Germany 4
32 USA 1
36 USA 2
39 Germany 5
43 USA 3
44 Germany 6
如何在 SQL 中编写它
解决方案
在 MySQL 8+ 中,您使用row_number()
:
select t.*,
row_number() over (partition by country order by CustomerID) as counter
from t;
在早期版本中,有多种方法。一种是相关子查询:
select t.*,
(select count(*)
from t t2
where t2.country = t.country and
t2.CustomerID <= t.CustomerID
) as counter
from t;
推荐阅读
- javascript - 如何在 HighCharts 中动态更改数据系列而不覆盖初始系列?
- r - 计算r中矩阵的并集
- marklogic - 使用 MarkLogic Data Hub Central 构建实体模型时,为什么使用 /instance 而不是 /header 创建范围路径索引?
- pandas - 快速过滤 numpy 数组中的值并获取 DataFrame 行的方法
- javascript - 8th Wall 为 Null 但 Aframe 中没有?
- javascript - 覆盖扩展字段是否替换扩展或添加它们?
- gradle - 如何在 gradle EXECUTION 步骤而不是 CONFIGURATION 步骤中运行 COPY?
- python - 使用生成器:“int() 参数必须是字符串、类似字节的对象或数字,而不是‘生成器’”
- javascript - 如果我在网址末尾添加“/”,则反应空白页面加载
- axios - 为什么获取请求会卡在“待处理”中