Sybase 查询自连接
Sybase query self-join
我有以下 table 存储 ID 和每个 ID 工作的部门。 (一个ID可以用多个部门,我想找一个只用一个部门的ID。
create table tempdb..dept (ID int, Dept varchar(10))
go
insert into tempdb..dept (ID, Dept) values (1, "HR")
insert into tempdb..dept (ID, Dept) values (2, "HR")
insert into tempdb..dept (ID, Dept) values (3, "HR")
insert into tempdb..dept (ID, Dept) values (4, "HR")
insert into tempdb..dept (ID, Dept) values (1, "Finance")
insert into tempdb..dept (ID, Dept) values (5, "Finance")
insert into tempdb..dept (ID, Dept) values (6, "Finance")
insert into tempdb..dept (ID, Dept) values (4, "Finance")
insert into tempdb..dept (ID, Dept) values (1, "IT")
insert into tempdb..dept (ID, Dept) values (7, "IT")
insert into tempdb..dept (ID, Dept) values (8, "IT")
insert into tempdb..dept (ID, Dept) values (4, "IT")
去
期望的输出:
ID Dept
2 HR
3 HR
5 Finance
6 Finance
7 IT
7 IT
您可以尝试 HAVING
count 从 table 获取 non-duplicate ID 然后使用 self-join
SELECT t2.*
FROM (
SELECT ID
FROM tempdb..dept
GROUP BY ID
HAVING COUNT(*) = 1
) t1 INNER JOIN tempdb..dept t2
ON t1.ID = t2.ID
您可以尝试使用相关子查询的另一种方式
SELECT t2.*
FROM tempdb..dept t2
ON t1.ID = t2.ID
WHERE EXISTS (
SELECT 1
FROM tempdb..dept tt
WHERE t2.ID = tt.ID
GROUP BY tt.ID
HAVING COUNT(*) = 1
)
我有以下 table 存储 ID 和每个 ID 工作的部门。 (一个ID可以用多个部门,我想找一个只用一个部门的ID。
create table tempdb..dept (ID int, Dept varchar(10))
go
insert into tempdb..dept (ID, Dept) values (1, "HR")
insert into tempdb..dept (ID, Dept) values (2, "HR")
insert into tempdb..dept (ID, Dept) values (3, "HR")
insert into tempdb..dept (ID, Dept) values (4, "HR")
insert into tempdb..dept (ID, Dept) values (1, "Finance")
insert into tempdb..dept (ID, Dept) values (5, "Finance")
insert into tempdb..dept (ID, Dept) values (6, "Finance")
insert into tempdb..dept (ID, Dept) values (4, "Finance")
insert into tempdb..dept (ID, Dept) values (1, "IT")
insert into tempdb..dept (ID, Dept) values (7, "IT")
insert into tempdb..dept (ID, Dept) values (8, "IT")
insert into tempdb..dept (ID, Dept) values (4, "IT")
去
期望的输出:
ID Dept
2 HR
3 HR
5 Finance
6 Finance
7 IT
7 IT
您可以尝试 HAVING
count 从 table 获取 non-duplicate ID 然后使用 self-join
SELECT t2.*
FROM (
SELECT ID
FROM tempdb..dept
GROUP BY ID
HAVING COUNT(*) = 1
) t1 INNER JOIN tempdb..dept t2
ON t1.ID = t2.ID
您可以尝试使用相关子查询的另一种方式
SELECT t2.*
FROM tempdb..dept t2
ON t1.ID = t2.ID
WHERE EXISTS (
SELECT 1
FROM tempdb..dept tt
WHERE t2.ID = tt.ID
GROUP BY tt.ID
HAVING COUNT(*) = 1
)