【问题标题】: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 子句中
【发布时间】:2023-03-09 05:49:01
【问题描述】:

我有以下表格:

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 子句中。

我错过了什么?

附加问题:

  • 是否有更快的查询来完成相同的结果?
  • 如何通过SkillsIds,例如(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 列,有没有办法不枚举 SelectGroup By 中的所有列,因为 Id 是唯一需要分组的列?

【问题讨论】:

标签: sql sql-server tsql


【解决方案1】:

首先,您的表格已损坏,除非Name 只有一个字符。你需要一个长度:

create table User (
  UserId int not null primary key clustered (Id),
  Name nvarchar(255) not null
);

总是在 SQL Server 中指定 char()varchar() 和相关类型时使用长度。

对于您的查询,SQL Server 不会使用 group by 处理 select *。列出selectgroup 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;

【讨论】:

  • 但是如果用户有 20 列并且我需要在输出中获取用户的所有列怎么办?我需要按所有列分组吗?我不能在 Group by 中使用 * 吗?
  • 关于 nvarchar 的长度是一个错字。我刚刚纠正了我在代码中检测到的一些错误。谢谢你的提示。
  • @MiguelMoura。 . .然后你应该问一个新的问题。这个问题是关于你的代码中的错误,这回答了这个问题。如果您对数据转换有特殊疑问,请提供示例数据、所需结果以及您想要做什么的说明。
  • @MiguelMoura 您需要阅读一本好的 SQL/关系数据库书籍,了解为什么这是不可能的。
猜你喜欢
  • 2014-05-14
  • 2014-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
相关资源
最近更新 更多