我有以下数据:
+---+----+
|Key|Name|
+---+----+
|1 |Tom |
+---+----+
|2 |Tom |
+---+----+
|3 |Dan |
+---+----+
|4 |Dan |
+---+----+
|5 |Dan |
+---+----+
|6 |Dan |
+---+----+
|7 |Ken |
+---+----+
|8 |Ken |
+---+----+
需要MySQL查询来获取此信息
+---+----+-----------+
|Key|Name| subtotal |
+---+----+-----------+
|1 |Tom | 2 |
+---+----+-----------+
|2 |Tom | 2 |
+---+----+-----------+
|3 |Dan | 4 |
+---+----+-----------+
|4 |Dan | 4 |
+---+----+-----------+
|5 |Dan | 4 |
+---+----+-----------+
|6 |Dan | 4 |
+---+----+-----------+
|7 |Ken | 2 |
+---+----+-----------+
|8 |Ken | 2 |
+---+----+-----------+
相同的数据,但附加列显示唯一名称的数量,来自名称列。我尝试使用count(1)和group by,但结果是3个名称条目和总数,但是我需要每条记录都有关于有多少记录具有与列名称相同的值的附加信息
答案 0 :(得分:2)
select t1.id, t1.name, t2.total
from your_table t1
join
(
select name, count(*) as total
from your_table
group by name
) t2 on t1.name = t2.name
答案 1 :(得分:0)
试试这个
select *, (sum(name)) as total from table
group by name
我认为这可以解决您的问题