我需要从sql中选择一个具有不同值的列

时间:2016-10-03 07:18:49

标签: sql

我获得了一个表,其中包含各个部门的列和另一个由各种dhdempno组成的列。我需要选择一个代表部门主管的唯一dhdempno。特定部门的多个员工具有相同的dhdmempno和一个独特的dhdempno,代表部门负责人。我应该执行什么查询才能获得结果?

实施例

Department - dhdempno
abc           1  
abc           1 
abc           2  
asd           5  
asd           5
asd           6

查询应该返回

abc    2
asd    6

6 个答案:

答案 0 :(得分:2)

这是一个查询,它将提供您正在寻找的结果。

select Department, dhdempno
from (
    SELECT Department, dhdempno, count(dhdempno) as counts
    FROM <your_table_name>
    group by Department, dhdempno ) as sub
where counts = 1;

答案 1 :(得分:1)

试试这个

select departmentid, count(distinct dhdempno) as counting from your_table
group by departmentid

答案 2 :(得分:0)

enter image description here使用像

这样的查询
SELECT DEPARTMENT,DHDEMPNO FROM DEPARTMENT
GROUP BY DEPARTMENT,DHDEMPNO
HAVING COUNT(DHDEMPNO)=1

将在各自的部门为您提供唯一的dhdempono记录

答案 3 :(得分:0)

SELECT DepartmentId, MAX(dhdempno)
FROM [Table-name]
GROUP BY DepartmentId

答案 4 :(得分:0)

select [Department],[dhdempno] from [dbo].[Your_Table_Name] where [dhdempno] in (select [dhdempno] from [dbo].[Your_Table_Name] group by [dhdempno] having count(*) = 1)

答案 5 :(得分:0)

使用以下查询:

select s.Department, max(s.dhdempno)as dhdempno from 
 (
   SELECT DISTINCT DEPARTMENT, dhdempno FROM DUMMY
 ) s group by s.Department