SQL - 从多个表中计数条目

时间:2017-03-15 21:25:00

标签: sql database db2

我有以下表格:

Table A:
+--------+
| name   |
+--------+
|  name1 |
|  name2 |
|  name3 |
+--------+

Table B:
+--------+----------+
| name   | someB    | 
+--------+----------+
|  name1 |    dorem |
|  name1 |    lorem |
|  name3 |    ipsum |
+--------+----------+

Table C:
+--------+----------+
| name   | someC    | 
+--------+----------+
|  name1 |    dorem |
|  name2 |    lorem |
|  name2 |    ipsum |
+--------+----------+

SQL如何计算每个名称的底部两个表中的条目?

结果应如下所示:

+--------+----+----+
| name   | A  | B  | 
+--------+----+----+
|  name1 |  2 |  1 |
|  name2 |  0 |  2 |
|  name3 |  1 |  0 |
+--------+----+----+

4 个答案:

答案 0 :(得分:1)

首先,您的数据结构存在问题。如果第一个表具有名称的唯一ID,则应在后续表中使用它。

但无论如何,你想在两个表中都有name计数。您可以使用union allgroup by

select name, sum(a) as a, sum(b) as b
from ((select name, 1 as a, 0 as b from t2) union all
      (select name, 0, 1 from t3)
     ) t
group by name;

答案 1 :(得分:1)

您可以在SELECT子句中使用相关子查询:

select name,
    (select count(*) from table2 t2 where t2.name = t1.name) as A,
    (select count(*) from table3 t3 where t3.name = t1.name) as B
from table1 t1

答案 2 :(得分:0)

试试这个:

SELECT C.name, COUNT(A.name),     COUNT(B.Name) 
   FROM C
   LEFT JOIN A ON C.name = A.name
   LEFT JOIN B ON C.name = B.name
   GROUP BY C.name

答案 3 :(得分:0)

select A.Name, B2.Nb as A, C2.Nb as B

from A

inner join lateral 
(
select count(*) Nb from B where B.Name=A.Name
) B2 on 1=1

inner join lateral 
(
select count(*) Nb from C where C.Name=A.Name
) C2 on 1=1