sql - SQL查询以获取包含所有B列的A列
问题描述
我有一张有 2 列 customer 和 city 的表。有 4 个独特的城市 (w,x,y,z) 我想要与所有城市相关联的客户。所以对于表
+----------+------+ | 客户 | 城市 | +----------+------+ | 一个 | W | | 一个 | X | | 一个 | 是 | | 一个 | Z | | 乙| X | | C | 是 | | Z | X | | Z | 是 | +----------+------+
所需的输出是
+----------+------+ | 客户 | 城市 | +----------+------+ | 一个 | W | | 一个 | X | | 一个 | 是 | | 一个 | Z | +----------+------+
我使用的查询是:
Select Customer,City
From Table As T
Where Exists (
Select 1
From Table As T2
Where T2.Customer = T.City
And T2.City<> T.City
)
解决方案
通过聚合和 HAVING 子句中的条件,您可以获得所需的客户:
select customer
from tablename
group by customer
having count(*) = (select count(distinct city) from tablename)
您可以将它与运算符 IN 一起使用:
select * from tablename
where customer in (
select customer
from tablename
group by customer
having count(*) = (select count(distinct city) from tablename)
)
推荐阅读
- django - 在服务器中显示类似 [Errno 5] 输入/输出错误的错误
- linux - 创建新的 linux 用户时 Postgre 数据库致命错误
- azure - 存储在 Azure Data Lake 中的 Oozie 文件或存档标记引用文件
- javascript - 当用户停止写入时发送 XMLHttpRequest
- java - 如何替换休息请求中的日期以使其成为今天的黄瓜自动化测试日期?
- c - Linux x86-64 系统调用挂钩,路径名乱码
- c++ - 代码中定义的变量列表(c++)
- azure-cosmosdb - CosmosDB API 选择:它是否规定了数据的存储方式,还是仅规定了我们与实例通信的方式?
- bash - Bash-Ubuntu 18.04-ROS-Melodic:Ping 到 IP 地址不返回任何内容
- mongodb - 如何使用 _id 作为时间戳将 createAt 字段添加到 Mongodb