我想在 sql server 上运行查询以选择表 (tableA) 中的所有元素,并从另一个表中聚合
select a.*, count(b.number) from tableA a
inner join tableB b on a.id = b.a_id
group by a.id;
这给出了以下错误:
错误:选择列表中的列 'a.id' 无效,因为它不包含在聚合函数或 GROUP BY 子句中。
SQLState:S1000
错误代码:8120
什么是得到我想要的正确查询?
我想在 sql server 上运行查询以选择表 (tableA) 中的所有元素,并从另一个表中聚合
select a.*, count(b.number) from tableA a
inner join tableB b on a.id = b.a_id
group by a.id;
这给出了以下错误:
错误:选择列表中的列 'a.id' 无效,因为它不包含在聚合函数或 GROUP BY 子句中。
SQLState:S1000
错误代码:8120
什么是得到我想要的正确查询?
你可以用那个
select a.*, x.number
from tableA a
inner join
(select b.a_id, count(b.number) number
from tableB b
group by b.a_id) x
on x.a_id = a.id
select a.*,
(Select count(b.number) from tableB b where b.a_id = a.id) as "b count"
from tableA a;
在具有 group by 的查询中,所有列都应该出现一个聚合函数或在 group by 列表中提及。您的错误是因为您的表“a”列除了 id 之外,没有按列表分组,也没有出现在聚合函数中。
select a.*, B.number
from tableA a
inner join
(
a.id a_id, count(b.number) number from tableA a
inner join tableB b on a.id = b.a_id
group by a.id;
) B on B.a_id = a.id
因为通过使用a.*,您正在从 中选择所有列tableA。使用聚合函数grouby或其他任何内容时,您必须在 group by 子句中提及列名。试试这个方法
select a.id,a.name, count(b.number) from tableA a
inner join tableB b on a.id = b.a_id
group by a.id,a.name
如果要从中选择所有列,tableA则不能使用分组依据。
select a.*, count(b.number) from tableA a
inner join tableB b on a.id = b.a_id