我有下表:
表格:
create table emp_project_mapping
(
emp_id varchar(10),
pro_id varchar(10)
)
记录:
insert into emp_project_mapping values('E101','P1'),
('E101','P2'),
('E102','P1'),
('E103','P3'),
('E104','P3'),
('E105','P4');
查询1 :查找从事多个项目的员工。
预期结果:
emp_id pro_id
--------------
E101 P1
E101 P2
查询2 :查找从事同一项目的多于一名员工。
emp_id pro_id
--------------
E103 P3
E104 P3
E101 P1
E102 P1
尝试:
查询1:
;WITH CTE
AS
(
SELECT emp_id,
pro_id,
DENSE_RANK() over(order by emp_id) empid_rank,
DENSE_RANK() over(order by pro_id) proid_rank
FROM emp_project_mapping
)
SELECT emp_id,pro_id
FROM CTE
WHERE empid_rank = 1 and proid_rank>1
输出:
emp_id pro_id
---------------
E101 P2
查询2:
;WITH CTE
AS
(
SELECT emp_id,
pro_id,
DENSE_RANK() over(order by emp_id) empid_rank,
DENSE_RANK() over(order by pro_id) proid_rank
FROM emp_project_mapping
)
SELECT emp_id,pro_id
FROM CTE
WHERE empid_rank > 1 and proid_rank = 1
输出:
emp_id pro_id
----------------
E102 P1
答案 0 :(得分:1)
您可以尝试这个。...
第一个解决方案
;WITH CTE
AS
(
SELECT emp_id,
pro_id,
ROW_NUMBER() OVER (PARTITION BY emp_id ORDER BY pro_id) empid_rank
FROM emp_project_mapping
)
SELECT * from emp_project_mapping WHERE emp_id IN (SELECT emp_id
FROM CTE
WHERE empid_rank > 1 )
第二种解决方法
;WITH CTE
AS
(
SELECT emp_id,
pro_id,
ROW_NUMBER() OVER (PARTITION BY pro_id ORDER BY emp_id) proid_rank
FROM emp_project_mapping
)
SELECT * FROM emp_project_mapping WHERE pro_id IN (SELECT pro_id
FROM CTE
WHERE proid_rank>1)