|
我有下表,包括两个字段,即a和b,如下所示:+ C! m5 p& M5 t8 F0 J
create table employe( empID varchar department varchar(10));插入一些记录:
* E$ @( F$ F5 `! G" f& H" kinsert into employe values('A101','Z'),('A101','X'),('A101','Y'),('A102','Z'),('A102','X A103','Z'),('A103','Y'),('A104','X'),('A104','Y'),('A105','Z'),('A106','X');select * from employe;empID department------------------A101 ZA101 XA101 YA102 ZA102 XA103 ZA103 YA104 XA104 YA105 ZA106 X注意/ B4 v& [+ l8 M7 |3 q K. r, {
:现在我想向员工展示独一无二的部门Z部门员工Y。所以,根据条件,只有A103应该显示员工,因为他只属于部门Z和部门Y。但是员工A101不应因属而出现Z,X,and Y。
' ~6 P9 I7 u/ \) O0 m. e预期结果 :2 }2 A8 `/ Y! V, o" [2 V1 K' X
若条件如下:Z,Y结果如下:# B5 f* H* b# H) k9 U& Q4 f% E
empID------A103若条件如下:Z,X结果如下:
* @* J0 t4 }+ S& d# w- e# G2 m/ {' RempID------A102若条件如下:Z,X并且Y后续结果应为:+ _( z' I) O: M+ v5 g1 M6 t
empID------A101注意 :我只想在那里where子句中执行此操作(不想使用groupbyandhaving因为我where该子句也将包含在另一个子句中。
& K6 N% C- @. s! R# a
% n( P' b3 s1 l 解决方案: 2 V/ a' d4 q7 [! l, c
第一个解决方案
; Y u, m. N) V2 fsqlfiddle
8 e; C" E, l. j' @SELECT empIdFROM SELECT empID,cc = COUNT(DISTINCT department) FROM employe WHERE department IN('Y','Z GROUP BY empID)tWHERE t.cc = 2 AND t.cc = SELECT COUNT(*) FROM employe WHERE empID = t.empID )第二个解决方案
b8 p& D9 y+ f6 L4 o. ssqlfiddle
3 o' A& O6 z2 d g5 w8 ^( ]SELECT e.empIdFROM employe eWHERE e.department IN('Y','Z')GROUP BY e.empIDHAVING COUNT(e.department) = 2 AND COUNT(e.department) = (SELECT COUNT(*) FROM employe WHERE empID = e.empId)不使用GROUP BY和HAVING:( o A) J) W" c
SELECT DISTINCT e.empIDFROM employe eWHERE EXISTS( SELECT 1 FROM employe WHERE department = 'Z' AND empID = e.empID ) AND EXISTS( SELECT 1 FROM employe WHERE department = 'Y' AND empID = e.empID ) AND NOT EXISTS( SELECT 1 FROM employe WHERE department NOT IN('Y','Z') AND empID = e.empID ) |
|