查询获取一对多和多对一员工项目关系
Query to get one to many and many to one employee project relationship
我有以下 table:
Table:
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
你可以试试这个....
对于第一个解决方案
;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)
我有以下 table:
Table:
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
你可以试试这个....
对于第一个解决方案
;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)