在sql中使用count和join

在sql中使用count和join,sql,join,union,Sql,Join,Union,有两张桌子上有国家名称,是来自这些国家的顶级足球俱乐部。我想加入这张桌子,数一数每个国家的俱乐部。以下代码不起作用: --表名称-表2017、表2018 select t.Country, COUNT(t.Country) as '2017 Countries', COUNT(a.Country) as '2018 countries' from table2017 as t Join table2018 as a on a.Country = t.Country group by

有两张桌子上有国家名称,是来自这些国家的顶级足球俱乐部。我想加入这张桌子,数一数每个国家的俱乐部。以下代码不起作用:

--表名称-表2017、表2018

select t.Country, COUNT(t.Country) as '2017 Countries',
       COUNT(a.Country) as '2018 countries'
from table2017 as t
Join table2018 as a
on a.Country = t.Country
group by t.Country
o/p

预期答复:

Country 2017 Countries  2018 countries
England       8              8
France        1              1
Germany       3              3
Italy         5              5
Spain         3              3
我做错了什么?

在加入之前,您需要聚合:


COUNT()。这两个计数在
联接之后是相同的,因此代码不会执行您想要的操作。

尝试为每个计数联接子查询

select 
    t1.country, t1Countries_2017, t2.Countries_2018
from 
    (select 
         t.Country, count(t.Country) Countries_2017
     from 
         table2017 
     group by 
         t.Country) t1 
inner join  
    (select 
         t.Country, count(t.Country) Countries_2018
     from 
         table2018
     group by 
         t.Country) t2 on t1.country = t2.country

样本输入和表格结构将是niceTable2017,table2018有两列:国家、足球俱乐部名称。有关表格概述:
select t2017.Country, t2017.num_2017, t2018.num_2018
from (select t.country, count(*) as num_2017
      from table2017 t
      group by t.country
     ) t2017 join
     (select t.country, count(*) as num_2018
      from table2018 t
      group by t.country
     ) t2018
     on t2017.Country = t2018.Country;
select 
    t1.country, t1Countries_2017, t2.Countries_2018
from 
    (select 
         t.Country, count(t.Country) Countries_2017
     from 
         table2017 
     group by 
         t.Country) t1 
inner join  
    (select 
         t.Country, count(t.Country) Countries_2018
     from 
         table2018
     group by 
         t.Country) t2 on t1.country = t2.country