2016-10-03 87 views
3

中選擇一個具有不同值的列我給出了一個表,其中包含各個部門的列和由各種dhdempno組成的另一列。我需要選擇一個代表部門負責人的獨特dhdempno。一個特定的部門有多個僱員,其中dhdmempno和一個代表部門負責人的獨特dhdempno。我應該執行什麼查詢以獲得結果?我需要從sql

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

查詢應返回

abc 2 
asd 6 
+0

你能解釋一下這個結果背後的邏輯嗎?你需要'選擇一個代表部門頭的獨特dhdempno'或者'查詢應該返回abc-2,asd-6' –

+1

爲什麼'asd-6'爲什麼不是'asd-2'? –

+0

您正在使用哪些DBMS? –

回答

1

試試這個

select departmentid, count(distinct dhdempno) as counting from your_table 
group by departmentid 
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; 
0

enter image description here使用查詢像

SELECT DEPARTMENT,DHDEMPNO FROM DEPARTMENT 
GROUP BY DEPARTMENT,DHDEMPNO 
HAVING COUNT(DHDEMPNO)=1 

會給你相應的部門具有獨特dhdempono記錄

+0

任何意見負面評論將不勝感激。因爲它的工作很好。 –

0
SELECT DepartmentId, MAX(dhdempno) 
FROM [Table-name] 
GROUP BY DepartmentId 
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) 
0

使用下面的查詢:

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