mysql - 在一个查询中组合多个列
问题描述
表 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'
我应该保留这些列,但联合不允许不同数量的列。
任何想法,将不胜感激
解决方案
您可以加入表以恢复与 中的每条记录关联的公司名称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 join
为left join
。
推荐阅读
- python - 我如何解决我在 python 中的元组的问题
- java - Vaadin 14 滑块
- spring - 映射基本 POJOS 的 ModelMapper 问题
- scala - 为什么不推荐使用符号“/:”
- scala - 避免使用隐式扩大类型?
- python - Python Tkinter中列表和字典的文本换行
- powershell - 使用 powershell 在 SSRS 中更改凭据检索
- node.js - 创建一个bat文件来运行节点命令
- c++ - 如何循环程序在 C++ 中请求新的输入集?
- ignite - 如何在 ignite-sql-api 中设置 rebalanceMode?