【发布时间】:2019-03-21 12:25:21
【问题描述】:
T1 是公司及其(多个用户)的表,T2 是注册用户的表。我计算了 T1 中的每家公司,有多少用户在 T2 中但需要 c3 出现在结果表中,#regUser == 0:
T1:
company user
c1 u1
c1 u2
c2 u2
c2 u3
c3 u4
c3 u1
T2:
user
u2
u3
所以结果表应该如下所示:
company #regUser
c1 1
c2 2
c3 0
使用以下代码,我只能获得非空公司的结果:
select t1s.company, count(1)
from (select * from t1) t1s
cross apply (select *
from t2 t2s
where t2s.reguser = t1s.[user]) t12s
group by t1s.company
谢谢
【问题讨论】:
-
这个查询过于复杂。例如,
from (select * from t1) t1s仅相当于from t1。你为什么不在两个表之间尝试一个简单的左连接? -
为什么用子查询来写?这可以简单地写成
select t1s.company, count(1) from t1 t1s JOIN t2 t2s ON t2s.reguser = t1s.[user] group by t1s.company