I have the following tables:
create table User
(
Id int not null primary key clustered (Id),
Name nvarchar(255) not null
)
create table dbo.UserSkill
(
UserId int not null,
SkillId int not null,
primary key clustered (UserId, SkillId)
)
Given a set of Skills Ids I need to get the users that have all these Skills Ids:
select Users.*
from Users
inner join UserSkills on Users.Id = UserSkills.UserId
where UserSkills.SkillId in (149, 305)
group by Users.Id
having count(*) = 2
I get the following error:
Column 'Users.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
What am I missing?
Side questions:
- Is there a faster query to accomplish the same result?
- How can I pass the
SkillsId
s, e.g. (149, 305) as a parameter? And set the@SkillsIds
count inhaving count(*) = 2
instead of2
?
UPDATE
The following code is working and I get the User John.
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, 'John'), (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
If user has 40 columns, is there a way to not enumerate all the columns in the Select
and Group By
since Id is the only column needed to group?