[英]Column 'Users.Reputation' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
[英]Column 'Users.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
我有以下表格:
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)
)
给定一组技能 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
我收到以下错误:
列“Users.Name”在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。
我错过了什么?
侧面问题:
SkillsId
s,例如 (149, 305) 作为参数? 并将@SkillsIds
计数设置为having count(*) = 2
而不是2
?更新
以下代码正在运行,我得到了用户 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
如果用户有 40 列,有没有办法不枚举Select
和Group By
中的所有列,因为 Id 是唯一需要分组的列?
首先,您的表格已损坏,除非Name
只有一个字符。 你需要一个长度:
create table User (
UserId int not null primary key clustered (Id),
Name nvarchar(255) not null
);
在 SQL Server 中指定char()
、 varchar()
和相关类型时始终使用长度。
对于您的查询,SQL Server 不会处理select *
和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.