Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 在同一个表中联接两个sql语句_Mysql_Sql - Fatal编程技术网

Mysql 在同一个表中联接两个sql语句

Mysql 在同一个表中联接两个sql语句,mysql,sql,Mysql,Sql,我有一张类似的桌子 Class City 01 xx 02 xx 03 yy 04 zz 我想要的结果是,选择类和Count of City,其中City=xx或City=yy Class Count 01 2 02 2 03 1 04 0 我不明白如何将不匹配的行也放入结果中。在本例中,类04的最后一行 感谢您的任何帮助您可以通过聚合来获得计数,然后返回结果: select t.cla

我有一张类似的桌子

Class  City
01      xx
02      xx   
03      yy  
04      zz   
我想要的结果是,选择类和Count of City,其中City=xx或City=yy

Class  Count
01      2 
02      2 
03      1
04      0 
我不明白如何将不匹配的行也放入结果中。在本例中,类04的最后一行


感谢您的任何帮助

您可以通过聚合来获得计数,然后返回结果:

select t.class, tc.cnt    
from table t join
     (select t.class, count(*) as cnt
      from table t
      group by class
     ) tc
     on tc.class = t.class;
试试下面的SQL:

SELECT t1.class, count(t2.class) AS COUNT FROM test t1
LEFT JOIN test t2 ON t1.city=t2.city AND t1.city in ('xx', 'yy')
GROUP BY t1.class, t1.city;
这将有助于您:

create table #cc (class int ,city varchar(2))
insert into #cc values (1,'xx')
insert into #cc values (2,'xx')
insert into #cc values (3,'yy')
insert into #cc values (4,'zz')
--insert into #cc values (1,'xx')


select class,isnull(c.cnt,0)
from #cc cc
left join (select city ,count(city) as cnt 
            from #cc c where city in ('xx','yy') 
            group by city ) c on c.city = cc.city

这可能符合您的目的:

选择TableMain.Class、TableJoin.CityCount 从TableMain 加入选择计数*作为城市计数,按城市从TableMain组中分类TableJoin 在TableJoin.Class=TableMain.Class上