以下sql...
declare @parent table (id int, description varchar(50))
declare @child table (parentid int, amount money)
insert into @parent(id, description) values (1, 'test')
insert into @child(parentid, amount) values (1, 3)
insert into @child(parentid, amount) values (1, 3)
select p.*,
sum(c.amount) as amount
from @parent p
inner join @child c on c.parentid = p.id
生成以下错误...
Msg 8120, Level 16, State 1, Line 10
Column '@parent.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
这解决了它...
select p.*,
sum(c.amount) as amount
from @parent p
inner join @child c on c.parentid = p.id
group by p.id,
p.description
如何更改它以便查询返回子记录的总和,但不使用 group by 表达式?也许是某种子查询?
最佳答案
您可以使用窗口功能:
select distinct p.*, sum(c.amount) over (partition by p.id) as amount
from @parent p inner join
@child c
on c.parentid = p.id;
您还可以使用应用
:
select distinct p.*, c.amount
from @parent p cross apply
(select sum(c.amount) as amount
from @child c
where c.parentid = p.id
) c;
关于sql - 不使用 group by 返回列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59969981/