Table A
+------------+--------------+--------------+
+ ID + Name + Company ID +
+------------+--------------+--------------+
+ 1 + Steve + 1 +
+ 2 + Mile + 2 +
+ 3 + Steve + 2 +
+ 4 + Del Piero + 2 +
+ 5 + Jack + +
============================+==============+
Table B
+------------+--------------+
+ ID + Company +
+------------+--------------+
+ 1 + A +
+ 2 + B +
============================+
What I want
+----------+------------+----------------+
+ # of id + # OF Name + # of B Company+
+----------+------------+----------------+
+ 5 + 4 + 3 +
+========================================+
I have tried Union//Union All
SELECT count(id), count(name) FROM table A
UNION
SELECT count(company) FROM table B where company = 'B'
I should keep these columns but Union doesn't allow a different number of columns.
Any ideas would be appreciated
You can join the tables to recover the company name associated to each record in tablea
, then aggregate:
select
count(*) no_ids,
count(distinct a.name) no_names,
sum(b.comany = 'B') no_b_company
from tablea a
inner join tableb b on b.id = a.company_id
Presumably, id
is the primary key of tablea
, so we just use count(*)
to summarize this column. no_names
counts how many different names can be seen in the corresponding column, and sum(b.company = 'B')
increase by 1
everytime company B is seen.
If there is a possibility of missing companies in tableb
, you can change the inner join
to a left join
.
Try this one
SELECT count(id),
count(name),
(SELECT count(company) FROM table B where company)
FROM table A
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.