I have the following SQL:
declare @Users table (
Id int not null primary key clustered (Id),
[Name] nvarchar(255) not null
);
declare @Skills table (
SkillId int not null primary key clustered (SkillId)
);
declare @UserSkills table (
UserId int not null,
SkillId int not null,
primary key clustered (UserId, SkillId)
);
insert into @Users
values (1, 'Jonh'), (2, 'Mary');
insert into @Skills
values (148), (149), (304), (305);
insert into @UserSkills
values (1, 149), (1, 305), (2, 148), (2, 149);
select u.Id, u.Name
from @Users as u
inner join @UserSkills as us
on u.Id = us.UserId
where us.SkillId in (149, 305)
group by u.Id, u.Name
having count(*) = 2
I am getting the User John as expected.
But in real code the User has 40 columns.
Is it possible to do the select / group by to use all columns without enumerating all individually?
Aggregate before joining:
select u.*
from @Users u join
(select us.UserId
from @UserSkills us
where us.SkillId in (149, 305)
group by us.UserId
having count(*) = 2
) us
on u.Id = us.UserId
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.