简体   繁体   中英

SQL - Count Entries from multiple tables

I have the following tables:

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 |
+--------+----------+

How would the SQL look like to count the entries from the bottom two tables for each name ?

The result should look like this:

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

First, you have a problem with your data structure. If the first table has unique ids for the names, then this should be used in the subsequent tables.

But in any case, you have name in both tables where you want to do the counts. You can use union all and group 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;

You can use correlated subqueries in the SELECT clause:

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

Try this:

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM