这是sqlfiddle上的代码 - http://sqlfiddle.com/#!6/9596d/8
create table tbla (uid nvarchar(10), name nvarchar(50));
create table tblb (uid nvarchar(10), cd nvarchar(5));
insert into tbla values ('abc','abraham lincoln');
insert into tbla values ('def','david copperfield');
insert into tblb values ('abc','a');
insert into tblb values ('abc','b');
insert into tblb values ('abc','c');
insert into tblb values ('def','a');
insert into tblb values ('def','c');
我需要退回计数。如果没有找到记录则返回0。这就是我所拥有的,但它不会为 uid def
返回0select a.uid, a.name, count(b.cd) as ct
from tblb b
left join
tbla a
on b.uid = a.uid
where b.cd = 'b'
group by a.uid, a.name
我做错了什么?它使用外连接。
答案 0 :(得分:1)
对于左连接,您的表已向后移动,并且您需要对where
表中的条件使用join子句而不是left join
子句。否则,您将left join
变为inner join
。
select a.uid, a.name, count(b.cd) as ct
from tbla a
left join tblb b
on b.uid = a.uid
and b.cd = 'b'
group by a.uid, a.name
rextester演示:http://rextester.com/ZXBS56241
返回:
+-----+-------------------+----+
| uid | name | ct |
+-----+-------------------+----+
| abc | abraham lincoln | 1 |
| def | david copperfield | 0 |
+-----+-------------------+----+
答案 1 :(得分:0)
恕我直言,这是正确的做法,
create table #tbla (uid nvarchar(10), name nvarchar(50));
create table #tblb (uid nvarchar(10), cd nvarchar(5));
insert into #tbla values ('abc','abraham lincoln');
insert into #tbla values ('def','david copperfield');
insert into #tblb values ('abc','a');
insert into #tblb values ('abc','b');
insert into #tblb values ('abc','c');
insert into #tblb values ('def','a');
insert into #tblb values ('def','c');
--select * from #tblb
--select * from #tbla
;With CTE as
(
select b.uid, count(b.cd) as ct
from #tblb b
where b.cd = 'b'
group by b.uid
)
select a.uid,isnull(c.ct,0),a.name from #tbla a
left join cte c on
a.uid=c.uid
drop table #tblb
drop table #tbla