首页 > 解决方案 > 在一个查询中组合多个列

问题描述

表 A

+------------+--------------+--------------+
+  ID        +  Name        +   Company ID +
+------------+--------------+--------------+
+   1        +  Steve       +      1       +
+   2        +  Mile        +      2       +
+   3        +  Steve       +      2       +
+   4        +  Del Piero   +      2       +
+   5        +  Jack        +              +
============================+==============+

表 B

+------------+--------------+
+  ID        +  Company     +
+------------+--------------+
+   1        +  A           +
+   2        +  B           +
============================+

我想要的是

+----------+------------+----------------+
+ # of id  +  # OF Name +  # of B Company+
+----------+------------+----------------+
+ 5        +  4         +  3             +
+========================================+

我试过Union//Union All

SELECT count(id), count(name) FROM table A
UNION 
SELECT count(company) FROM table B where company = 'B'

我应该保留这些列,但联合不允许不同数量的列。

任何想法,将不胜感激

标签: mysqlsqlgroup-bycount

解决方案


您可以加入表以恢复与 中的每条记录关联的公司名称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

想必,id是 的主键tablea,所以我们只是用count(*)这个栏目来总结一下。no_names计算在相应列中可以看到多少个不同的名称,并且每次看到公司 B 都会sum(b.company = 'B')增加。1

如果有可能缺少公司tableb,您可以将其更改inner joinleft join


推荐阅读