sql在仍然拥有所有行值的情况下对发生的事件进行计数

zsbz8rwp  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(633)

这是我所在部门的某个人提出的请求,但我在编写时遇到了问题,无法既保留列中出现的总数,又保留行。
为了简单起见,这样的表:

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
kognpnkq

kognpnkq1#

你可以试试这个,写一个子查询 COUNTLocation 然后是自己 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

sqlfiddle:http://sqlfiddle.com/#!9/8cf/3号
结果

| Name | Location | Total |
+-------+----------+-------+
| Sam | Ohio | 3 |
| John | Ohio | 3 |
| Dave | Ohio | 3 |
| James | Virginia | 2 |
| Cindy | Virginia | 2 |
| Fred | Idaho | 1 |

ee7vknir

ee7vknir2#

可以使用窗口函数

select distinct name, location, count(*) over(partition by location) 
from table1

这是从 MySQL >= 8

相关问题