[英]Column 'Users.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
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:给定一组技能 ID,我需要获取拥有所有这些技能 ID 的用户:
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.
列“Users.Name”在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。
What am I missing?我错过了什么?
Side questions:侧面问题:
SkillsId
s, eg (149, 305) as a parameter?SkillsId
s,例如 (149, 305) 作为参数? And set the @SkillsIds
count in having count(*) = 2
instead of 2
?@SkillsIds
计数设置为having count(*) = 2
而不是2
? UPDATE更新
The following code is working and I get the User John.以下代码正在运行,我得到了用户 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?如果用户有 40 列,有没有办法不枚举
Select
和Group By
中的所有列,因为 Id 是唯一需要分组的列?
First, your tables are broken, unless Name
has only a single character.首先,您的表格已损坏,除非
Name
只有一个字符。 You need a length:你需要一个长度:
create table User (
UserId int not null primary key clustered (Id),
Name nvarchar(255) not null
);
Always use a length when specifying char()
, varchar()
, and related types in SQL Server.在 SQL Server 中指定
char()
、 varchar()
和相关类型时始终使用长度。
For your query, SQL Server, is not going to process select *
with group by
.对于您的查询,SQL Server 不会处理
select *
和group by
。 List each column in both the select
and group by
:列出
select
和group by
每一列:
select u.id, u.name
from Users u join
UserSkills us
on u.Id = us.UserId
where us.SkillId in (149, 305)
group by u.Id, u.name
having count(*) = 2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.