首页 > 解决方案 > 从sql中的列中选择特定值

问题描述

我的原始数据集看起来与下面提到的示例数据集非常相似:

ID 姓名 国家
1 罗恩 我们 人力资源
2 约翰 我们 人力资源
2 约翰 我们
2 约翰 我们
3 凯利 我们
3 凯利 我们
4 戴夫 我们 销售量
4 戴夫 我们
4 戴夫 我们
4 戴夫 我们 营销
5 诺拉 我们

我想显示那些只在 IT 部门工作过的员工的姓名。例如,John 曾在 HR 和 IT 部门工作,所以我想从我的输出中排除他的名字。我的方法在 SQL Server 中应该是什么?

基于上面的例子,我的输出应该如下表所示:

ID 姓名 国家
3 凯利 我们
3 凯利 我们
5 诺拉 我们

标签: sqlsql-servertsql

解决方案


有几种方法,一种是使用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'

推荐阅读