Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 两种无group by子句聚合函数的比较_Sql_Oracle - Fatal编程技术网

Sql 两种无group by子句聚合函数的比较

Sql 两种无group by子句聚合函数的比较,sql,oracle,Sql,Oracle,假设我们有3个表,第一个表是主表,下面是详细信息 主表(Id、col1、col2) ChildTable1(Id、MasterId、Amount1) ChildTable2(Id、MasterId、Amount2) 我必须从主表中找到id,其中sum(chiletable1.Amount1)应该大于sum(chiletable2.Amount2) 我已经使用groupby和having子句编写了查询,其中包含正确的数据 如果表中有数以十亿计的记录,那么有没有其他方法可以在不使用groups的情况

假设我们有3个表,第一个表是主表,下面是详细信息

主表(Id、col1、col2)

ChildTable1(Id、MasterId、Amount1)

ChildTable2(Id、MasterId、Amount2)

我必须从主表中找到id,其中
sum(chiletable1.Amount1)
应该大于
sum(chiletable2.Amount2)

我已经使用groupby和having子句编写了查询,其中包含正确的数据

如果表中有数以十亿计的记录,那么有没有其他方法可以在不使用groups的情况下编写相同的查询。 以下是我的疑问

    select Mastertable.Id 
           from Mastertable,Childtable1,ChildTable2
           where Mastertable.Id=Childtable1.MasterId
                 and ChildTable1.MasterId=ChildTable2.MasterId
                 group by MasterTable.Id
                 having SUM(Childtable1.Amount1) > SUM(Childtable2.Amount2)
回答你的问题,不

原因很简单:没有
groupby
你就不能有
SUM()
s。(除了可能的总数)


EDIT:嗯,可能是一个带有循环、游标等的存储过程,但那肯定是一个杀伤力过大的问题!;)

好吧,你必须在某个时候分组,所以我不知道你为什么不想分组

您可以尝试按子表中的ID进行分组:

SELECT M.Id
FROM Mastertable M
INNER JOIN (SELECT MasterID, 
                   SUM(Amount) Amount 
            FROM Childtable1 
            GROUP BY MasterID) C1
    ON M.Id = C1.MasterID
INNER JOIN (SELECT MasterID, 
                   SUM(Amount) Amount 
            FROM Childtable2 
            GROUP BY MasterID) C2
    ON M.Id = C2.MasterID
WHERE C1.Amount > C2.Amount

如果有一个外键返回到
主表
,或者子表中的
主ID
上有一个索引,这可能是不通过快照或其他方法预聚合的最快方法。

我强烈怀疑
group by
是执行查询的最快方法。如果在子表中存在特定的主ID,该怎么办两个
子表中的一个
,但不是两个?