MySQL: use column value in same row for count
How do I use a value from another column so that I can create another column with a sum of the same type.
eg.
+---------+------+
| name | team |
+---------+------+
| Michael | red |
| Lebron | blue |
| Ben | red |
| Tiger | red |
| John | blue |
+---------+------+
Output:
+---------+------+----------------+
| name | team | member_counter |
+---------+------+----------------+
| Michael | red | 3 |
| Lebron | blue | 2 |
| Ben | red | 3 |
| Tiger | red | 3 |
| John | blue | 2 |
+---------+------+----------------+
As you can see there are 3 reds and 2 blues. Anyway, can I use the value of the previous columns? count (command = previous column)? how is member_counter?
source to share
-
If you only want an output like this, you can do:
SELECT T1.name,T1.team,T2.member_count FROM TableName T1 JOIN (SELECT name,team,count(team) as member_count FROM TableName GROUP BY team) T2 ON T1.team=T2.team
Result:
name team member_count ---------------------------- Michael red 3 Lebron blue 2 Ben red 3 Tiger red 3 John blue 2
Example in SQL Fiddle .
-
If you are trying to add another column
member_counter
to your table, you can do this:ALTER TABLE TableName ADD member_counter INT NULL UPDATE TableName a JOIN (SELECT name,team,COUNT(team) as member_counter FROM TableName b GROUP BY team) b ON a.name = b.name AND a.team=b.team SET a.member_counter = b.member_counter
Example in SQL Fiddle .
source to share
Just do the subquery:
select *, (select count(*) from table t2 where t1.team = t2.team) as member_counter
from table t1
EDIT:
I have checked 1 million lines. The execution plans for this request and the request from the received response are 99% identical. With time statistics, both queries do exactly the same thing. With IO statistics, both queries are executed exactly the same. And now I just can't figure out why I got down. The only difference in my version is shorter and clearer.
EDIT2:
This is a working fiddle:
select *, (select count(*) from tmp t2 where t1.team = t2.team) as member_counter
from tmp t1
source to share