这是我所在部门的某个人提出的请求,但我在编写时遇到了问题,无法既保留列中出现的总数,又保留行。
为了简单起见,这样的表:
Name Location
Dave Ohio
Sam Ohio
James Virginia
Fred Idaho
Cindy Virginia
John Ohio
但我需要它看起来像这样:
Name Location Total
Dave Ohio 3
Sam Ohio 3
John Ohio 3
James Virginia 2
Cindy Virginia 2
Fred Idaho 1
所以我的尝试是:
select Name, Location, count(Location) as 'Total'
from table1
group by Location
给了我
Name Location Total
Fred Idaho 1
Dave Ohio 1
John Ohio 1
Sam Ohio 1
Cindy Virginia 1
James Virginia 1
2条答案
按热度按时间kognpnkq1#
你可以试试这个,写一个子查询
COUNT
由Location
然后是自己JOIN
```SELECT
t.Name,t.Location,t1.Total
FROM
T t
INNER JOIN
(SELECT Location,count(*) Total
FROM T
GROUP BY Location) t1 ON t.Location = t1.Location
ORDER BY
t1.Total DESC
| Name | Location | Total |
+-------+----------+-------+
| Sam | Ohio | 3 |
| John | Ohio | 3 |
| Dave | Ohio | 3 |
| James | Virginia | 2 |
| Cindy | Virginia | 2 |
| Fred | Idaho | 1 |
ee7vknir2#
可以使用窗口函数
这是从
MySQL >= 8