sql - 从sql中的列中选择特定值
问题描述
我的原始数据集看起来与下面提到的示例数据集非常相似:
ID | 姓名 | 国家 | 部 |
---|---|---|---|
1 | 罗恩 | 我们 | 人力资源 |
2 | 约翰 | 我们 | 人力资源 |
2 | 约翰 | 我们 | 它 |
2 | 约翰 | 我们 | 它 |
3 | 凯利 | 我们 | 它 |
3 | 凯利 | 我们 | 它 |
4 | 戴夫 | 我们 | 销售量 |
4 | 戴夫 | 我们 | 它 |
4 | 戴夫 | 我们 | 它 |
4 | 戴夫 | 我们 | 营销 |
5 | 诺拉 | 我们 | 它 |
我想显示那些只在 IT 部门工作过的员工的姓名。例如,John 曾在 HR 和 IT 部门工作,所以我想从我的输出中排除他的名字。我的方法在 SQL Server 中应该是什么?
基于上面的例子,我的输出应该如下表所示:
ID | 姓名 | 国家 | 部 |
---|---|---|---|
3 | 凯利 | 我们 | 它 |
3 | 凯利 | 我们 | 它 |
5 | 诺拉 | 我们 | 它 |
解决方案
有几种方法,一种是使用not exists
select *
from t
where department='it'
and not exists (select * from t t2 where t2.id=t.id and t2.department !='it')
另一种方法是使用聚合窗口函数:
select id, name, country, department from (
select *,
Min(department) over(partition by id) mind,
Max(department) over(partition by id) maxd
from t
)t
where mind=maxd and maxd='it'
推荐阅读
- java - 为什么找不到方法?
- javascript - js为每个键返回bug
- javascript - 新的 HTML 元素不适用于拖放功能
- python - DataFrame 不允许用于重采样的时间戳转换
- java - Android - 如何在清单文件中设置自定义工具栏的标题?标签属性不起作用
- c - 搜索向量中出现两次的所有整数
- java - 为什么引入兄弟模块会改变 gradle 5 中该模块的依赖规则/顺序?
- javascript - for 循环中的几个异步调用,需要知道所有调用何时使用 observables 完成
- swagger-ui - 我们可以在 spring boot 1.3 和 java 6 中使用 swagger 吗?
- json - 如何使用 golang+jason 从命名的 json 中获取数据?