相关表中的SQL GROUP BY列

时间:2017-04-06 09:37:55

标签: sql select group-by db2

我有表T1

ID     RESOLVER   RESOLVEDBY
1      A          GROUP1
2      A          GROUP1
3      A          GROUP1
4      B          GROUP1
5      B          GROUP1

我还有表T2

GROUPID   GROUP      PERSON
1         GROUP1     A      
2         GROUP1     B
3         GROUP1     C

我做了这个SQL查询,它返回每个人解析了多少条记录

select resolver,count(*) from T1
where resolvedby='GROUP1'
group by resolver

并正确返回

A 3
B 2

但是,我还想为属于该组的所有人检索此统计信息,因此对于用户C,我希望值为0。 所以最终的结果应该是

A 3
B 2
C 0

4 个答案:

答案 0 :(得分:1)

根据您的修改:

您需要将现有的Select加入第二个表:

select t2.person, coalesce(cnt, 0)
from T2
left join
 ( -- aggregate before join (usually more efficient)
   select resolver,count(*) as cnt
   from T1
   where resolvedby='GROUP1'
   group by resolver
 ) as T1
on T1.resolver=T2.person
where t2."GROUP"='GROUP1' -- adding double quotes as GROUP is usually a keyword

答案 1 :(得分:1)

外部将计数加入人员表。当T2中没有条目时,使用COALESCE显示0。

select t2.person, t2.group, coalesce(counted.cnt, 0)
from t2
left join
(
  select resolver, resolvedby, count(*) as cnt
  from T1
  group by resolver, resolvedby
) counted on counted.resolver = t2.person and counted.resolvedby = t2.group
where t2.group = 'GROUP1';

您也可以在select子句中使用子查询:

select 
  t2.person, 
  t2.group, 
  (select count(*) from t1 where t1.resolver = t2.person and t1.resolvedby = t2.group)
from t2
where t2.group = 'GROUP1';

答案 2 :(得分:0)

您需要外部联接才能从T2返回所有记录。以下查询使用RIGHT OUTER JOIN从T2返回所有行(即包括C的行)并获取每个行的匹配计数:

select T2.PERSON, count(T1.ID) from T1
right outer join T2 on T2.PERSON=T1.RESOLVER 
where T2.group ='GROUP1' -- If this was T1.group, we'd have to use COALESCE() to prevent dropping out rows in T2 that don't have a resolution in T1 
group by T2.PERSON

上面,我们使用右外连接,因为我们需要从表/表达式到语句right outer join的所有行。如果我们首先使用FROM编写了查询T2子句,那么它将是左外连接,如下所示:...T2 left outer join T1...

答案 3 :(得分:0)

使用以下查询根据您的要求获得预期输出。

select person,count(resolver) from t2 left join t1 on t2.groups=t1.groups and t2.person = t1.resolver  group by person;

OUTPUT : 

mysql> select person,count(resolver) from t2 left join t1 on t2.person = t1.resolver  group by person;
+--------+-----------------+
| person | count(resolver) |
+--------+-----------------+
| A      |               4 |
| B      |               3 |
| C      |               0 |
+--------+-----------------+
3 rows in set (0.01 sec)