Sql 列';Users.Name';在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中
我有以下表格:Sql 列';Users.Name';在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有以下表格: 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,
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子句中
我错过了什么
附带问题:
- 是否有更快的查询来实现相同的结果
- 如何将
s,例如(149305)作为参数传递?并将SkillsId
计数设置为@SkillsIds
中的count(*)=2而不是
2
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
和groupby
中的所有列,因为Id是分组所需的唯一列?首先,您的表被破坏,除非Name
只有一个字符。您需要一个长度:
create table User (
UserId int not null primary key clustered (Id),
Name nvarchar(255) not null
);
在SQL Server中指定char()
、varchar()
和相关类型时,始终使用长度
对于您的查询,SQL Server不会使用groupby
处理select*
。列出选择
和分组依据
中的每一列:
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;
您通常按照与所选列相同的列进行分组,但作为设置函数参数的列除外。向我们展示一些示例表数据和预期结果-。这是否回答了您的问题@jarlh我刚刚用这样的代码添加了一个更新,但若用户有20列,我需要在输出中获取所有用户列,该怎么办?我需要按所有列分组吗?我不能在Group by中使用*吗?关于nvarchar中的长度,这是一个打字错误。我刚刚纠正了代码中检测到的一些错误。谢谢你的提示。@MiguelMoura。那么你应该问一个新问题。这个问题是关于代码中的错误的,这个问题回答了这个问题。如果您对数据转换有特殊疑问,请提供示例数据、期望的结果以及对您希望执行的操作的解释。@MiguelMoura您需要阅读一本好的SQL/关系数据库书籍,以了解为什么这是不可能的。