sql - 不使用 group by 返回列的总和

标签 sql sql-server

以下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/

相关文章:

java - SQL:如何进行查询,检查列上具有特定值的行是否多次引用外键?

sql - 如何将两个表中的列合并为一个输出?

java - Controller 方法 java ee sql 未读取表单元素

php - 数据库条目被删除

sql - 如何在没有子查询的情况下找到最大值

sql - 多列上的 SELECT COUNT(DISTINCT...) 错误?

sql-server - 奥尔良 - 将 Cereal 持久保存到 'traditional' 表和列中

sql-server - 合并声明和身份插入

mysql - 从现在到一周 MYSQL 从客户那里获取生日

sql - Oracle 11g CREATE VIEW 使用 CONNECT BY 和多个表