[英]SQL Group By and Count on two columns
I have a MySQL table with data as:- 我有一个数据表的MySQL表: -
country | city
---------------
italy | milan
italy | rome
italy | rome
ireland | cork
uk | london
ireland | cork
I want query this and group by the country and city and have counts of both the city and the country, like this:- 我想查询这个并按国家和城市分组,并计算城市和国家,如下: -
country | city | city_count | country_count
---------------------------------------------
ireland | cork | 2 | 2
italy | milan | 1 | 3
italy | rome | 2 | 3
uk | london | 1 | 1
I can do:- 我可以:-
SELECT country, city, count(city) as city_count
FROM jobs
GROUP BY country, city
Which gives me:- 这给了我: -
country | city | city_count
-----------------------------
ireland | cork | 2
italy | milan | 1
italy | rome | 2
uk | london | 1
Any pointer to getting the country_count too? 任何指向获取country_count的指针?
You can just do it in subquery on results. 您可以在结果的子查询中执行此操作。
SELECT jm.country, jm.city,
count(city) as city_count,
(select count(*) from jobs j where j.country = jm.country) as country_count
FROM jobs jm
GROUP BY jm.country, jm.city
SELECT country, city, count(city) as city_count, count(country) as country_count FROM jobs GROUP BY country, city
我将您的数据复制到一个表并运行此查询,它给了我想要的结果。
Use Self Join Instead. 相反,请使用自联接。
select a.country,a.city,b.city_count,c.country_count
from jobs a
inner join (select count(1) as city_count, city
from jobs
group by city
) b on a.city = b.city
inner join (select count(1) as country_count, country
from jobs
group by country
) c on a.country = c.country
group by country,city
i have written answer at that time Giorgos Betsos posted answer the same as my code so i have written in CTE also 我当时写的答案Giorgos Betsos发布的回答与我的代码相同,所以我也用CTE写过
we can achieve result in lot ways but here is the 2 solutions and second query is less complicated 我们可以通过很多方式实现结果,但这里是2个解决方案,第二个查询不那么复杂
declare @Table1 TABLE
([country] varchar(7), [city] varchar(6))
;
INSERT INTO @Table1
([country], [city])
VALUES
('italy', 'milan'),
('italy', 'rome'),
('italy', 'rome'),
('ireland', 'cork'),
('uk', 'london'),
('ireland', 'cork')
;
First way 第一种方式
;with CTE AS (
select T.country,T.city,count(T.city)TCity from @Table1 T
group by country,city )
select C.country,C.city,C.TCity,T.T from CTE C INNER JOIN (select count(country)T,country from @Table1 group by country )T
ON T.country = C.country
GROUP BY c.country,c.city,c.TCity,t.t
Second way 第二种方式
SELECT country, city, count(city) as citycnt,
(SELECT count(*)
FROM @Table1 AS TT
WHERE T.country = TT.country) AS countrycnt
FROM @Table1 AS T
GROUP BY country, city
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.