我有一张类似的表,
Class City
01 xx
02 xx
03 yy
04 zz
我想要的结果是,(选择城市的类别和数量=城市= xx或城市= yy)
Class Count
01 2
02 2
03 1
04 0
我无法理解的方法是将不匹配的行放入结果中。在这个例子中是Class 04的最后一行。
任何帮助表示赞赏
答案 0 :(得分:0)
您可以通过聚合来获取计数,然后加入结果:
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;
答案 1 :(得分:0)
尝试以下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;
<强> SQL Fiddle 强>
答案 2 :(得分:0)
这可以帮到你:
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
答案 3 :(得分:0)
这可能适合您的目的:
SELECT TableMain.Class,TableJoin.CityCount
来自TableMain
JOIN(选择COUNT(*)作为CityCount,Class FROM TableMain GROUP BY City)TableJoin
ON TableJoin.Class = TableMain.class;