澄清后,我对问题的理解是:归还那些只从单一出版商那里借书的员工。
您可以通过COUNT(DISTINCT publisher)
在您的HAVING
子句中使用来做到这一点。
像这样:
declare @employee table (id int);
declare @books table (isbn int, title varchar(50), publisher varchar(50));
declare @loan table (employee_id int, book_isbn int);
insert @employee values (1000);
insert @employee values (1001);
insert @employee values (1002);
insert @books values (1, 'Some Book', 'Publisher A');
insert @books values (2, 'Some Book', 'Publisher A');
insert @books values (3, 'Some Book', 'Publisher A');
insert @books values (4, 'Some Book', 'Publisher B');
insert @books values (5, 'Some Book', 'Publisher B');
insert @books values (6, 'Some Book', 'Publisher B');
insert @loan values (1000, 1);
insert @loan values (1000, 2);
insert @loan values (1001, 3);
insert @loan values (1001, 4);
insert @loan values (1001, 5);
-- Show the number of different publishers per employee
select e.id, count(*) as ecount, count(DISTINCT b.publisher) as publishers
from @employee e
inner join @loan l on e.id = l.employee_id
inner join @books b on l.book_isbn = b.isbn
group by e.id
-- yields: id ecount publishers
-- ----------- ----------- -----------
-- 1000 2 1
-- 1001 3 2
-- Filter on the number of different publishers per employee
select e.id, count(*) as ecount
from @employee e
inner join @loan l on e.id = l.employee_id
inner join @books b on l.book_isbn = b.isbn
group by e.id
having count(DISTINCT b.publisher) = 1
-- yields: id ecount
-- ----------- -----------
-- 1000 2