计算某个值在 SQL 中非 GROUP BY 列中出现的次数
count number of times a value appears in a column not GROUP BY in SQL
让我们假设有以下 table(没有 CountX 列):
| **ID** | **Name** | **City** | **CountX** |
| 1 | Ana | London | 1 |
| 2 | Ana | Paris | 1 |
| 3 | Mary | Paris | 2 |
| 4 | Mary | Paris | 2 |
| 5 | John | London | 2 |
| 6 | John | London | 2 |
我想添加包含不同条目数的列 'CountX',每个名称和城市的组合。
我尝试使用 ROW_NUMBER() 但效果不佳:
ROW_NUMBER () OVER (PARTITION BY Name, City ORDER BY Name) AS CountX
我也尝试过使用 select distinct Name from table GROUP BY Name
进行子查询,但不能
提前致谢!
使用 window 函数。 . .但是 count(*)
:
select count(*) over (partition by name, city) as countx
让我们假设有以下 table(没有 CountX 列):
| **ID** | **Name** | **City** | **CountX** |
| 1 | Ana | London | 1 |
| 2 | Ana | Paris | 1 |
| 3 | Mary | Paris | 2 |
| 4 | Mary | Paris | 2 |
| 5 | John | London | 2 |
| 6 | John | London | 2 |
我想添加包含不同条目数的列 'CountX',每个名称和城市的组合。
我尝试使用 ROW_NUMBER() 但效果不佳:
ROW_NUMBER () OVER (PARTITION BY Name, City ORDER BY Name) AS CountX
我也尝试过使用 select distinct Name from table GROUP BY Name
进行子查询,但不能
提前致谢!
使用 window 函数。 . .但是 count(*)
:
select count(*) over (partition by name, city) as countx