SQL Group By和Count两列

时间:2015-10-02 05:26:02

标签: mysql sql group-by

我有一个MySQL表,数据为: -

country | city
---------------
italy   | milan
italy   | rome
italy   | rome
ireland | cork
uk      | london
ireland | cork

我想查询这个并按国家和城市分组,并且计算城市和国家/地区,如下: -

country | city   | city_count | country_count
---------------------------------------------
ireland | cork   |          2 |             2
italy   | milan  |          1 |             3
italy   | rome   |          2 |             3
uk      | london |          1 |             1

我能做到: -

SELECT country, city, count(city) as city_count
FROM jobs
GROUP BY country, city

这给了我: -

country | city   | city_count 
-----------------------------
ireland | cork   |          2 
italy   | milan  |          1 
italy   | rome   |          2
uk      | london |          1

指向获取country_count的任何指针?

5 个答案:

答案 0 :(得分:2)

您可以使用相关的子查询:

SELECT country, city, count(city) as city_count,
       (SELECT count(*)
        FROM jobs AS j2
        WHERE j1.country = j2.country) AS country_count
FROM jobs AS j1
GROUP BY country, city

Demo here

答案 1 :(得分:1)

您可以在结果的子查询中执行此操作。

  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

SQL Fidlle example

答案 2 :(得分:0)

SELECT country, city, count(city) as city_count, count(country) as country_count FROM jobs GROUP BY country, city

我将您的数据复制到一个表中并运行此查询,它给了我想要的结果。

答案 3 :(得分:0)

使用自我加入。

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

答案 4 :(得分:0)

我当时写的答案Giorgos Betsos发布的答案和我的代码一样,所以我也用CTE写了

我们可以通过多种方式实现结果,但这里是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')
;

第一种方式

   ;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

第二种方式

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