[英]combining multiple columns in one query
Table A表A
+------------+--------------+--------------+
+ ID + Name + Company ID +
+------------+--------------+--------------+
+ 1 + Steve + 1 +
+ 2 + Mile + 2 +
+ 3 + Steve + 2 +
+ 4 + Del Piero + 2 +
+ 5 + Jack + +
============================+==============+
Table B表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我试过 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.我应该保留这些列,但 Union 不允许使用不同数量的列。
Any ideas would be appreciated任何想法,将不胜感激
You can join the tables to recover the company name associated to each record in tablea
, then aggregate:您可以加入这些表以恢复与tablea
每条记录关联的公司名称,然后聚合:
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.想必id
是tablea
的主键,所以我们只用count(*)
来总结这一列。 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. no_names
计算在对应列中可以看到多少个不同的名称,每次看到公司 B 时sum(b.company = 'B')
增加1
。
If there is a possibility of missing companies in tableb
, you can change the inner join
to a left join
.如果tableb
可能缺少公司,您可以将inner join
更改为left join
。
Try this one试试这个
SELECT count(id),
count(name),
(SELECT count(company) FROM table B where company)
FROM table A
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.