Sql 带子查询的Having子句

Sql 带子查询的Having子句,sql,oracle,Sql,Oracle,我有下面的情景 CREATE TABLE plch_sales ( region VARCHAR2 (100), product VARCHAR2 (100), amount NUMBER ) / INSERT INTO plch_sales VALUES ('North', 'Magic Wand', 1000); INSERT INTO plch_sales VALUES ('North', 'Skele-Gro', 1000); INSERT

我有下面的情景

CREATE TABLE plch_sales
(
   region      VARCHAR2 (100),
   product     VARCHAR2 (100),
   amount   NUMBER
)
/

INSERT INTO plch_sales VALUES ('North', 'Magic Wand',  1000);
INSERT INTO plch_sales VALUES ('North', 'Skele-Gro',   1000);
INSERT INTO plch_sales VALUES ('North', 'Timeturner ', 1000);
INSERT INTO plch_sales VALUES ('South', 'Portkey',     1000);
INSERT INTO plch_sales VALUES ('South', 'Quaffle',     1000);
INSERT INTO plch_sales VALUES ('West',  'Imperius',    1000);
INSERT INTO plch_sales VALUES ('West',  'Gringotts',   1000);
COMMIT;
为什么下面的查询不生成行?数据库是oracle

select region, sum(amount) sm_amount from PLCH_SALES group by region having sum(amount) > (select sum(amount)/3 from PLCH_SALES);
你需要先求和,然后除以3,如下所示-

SELECT region, SUM(amount) sm_amount
FROM PLCH_SALES
GROUP BY region
HAVING SUM(amount) > (SELECT SUM(amount)FROM PLCH_SALES)/3;
或者您也可以尝试使用窗口聚合函数


你的写作方式与从句无关

有多种方法可以像使用CTE、Parent_table或下面的类似工具一样进行此操作:

select region, sum(amount) sm_amount 
from PLCH_SALES 
group by region 
having sum(amount) >(sum(amount)/3 )

)

您的查询应该有效。子查询返回:

2333.333333333333333333333333333333333333
没有返回值的查询:

很明显,“北方”应该在结果集中

然而,它在Oracle中并不存在。他是一把小提琴。它确实适用于子查询:

select x.*
from (select region, sum(amount) as sm_amount, (select sum(amount)/3 from PLCH_SALES) as thirds
      from PLCH_SALES
      group by region
     ) x
where sm_amount > thirds ;
它确实与CTE一起工作:

with thirds as (
      select sum(s2.amount)/3 as val from PLCH_SALES s2
     )
select region, sum(amount) sm_amount
from PLCH_SALES
group by region
having sum(amount) > (select val from thirds);
这听起来像个虫子

查询在其他数据库中工作:


毫无疑问,任何其他数据库都会尝试使用它。

您到底想要什么?我想说的是,这是一个bug…这将返回行。>从PLCH_Sales中选择sumamount/3+0我可以问一下为什么需要先求和,然后除以3吗?OP最初的查询没有给出结果的原因是什么?@Sujitmohanty30,通常它应该在OP的查询中返回结果,但在所有数据库中检查后,我觉得这是Oracle特有的-您可以在这里检查是的,实际上我注意到另一件事,如果我们只是将PLCH_SALES中相同的语句select SUMMOUNT/3+0放入select值中,它甚至可以在OP的查询中工作。奇怪的行为……你有没有检查我对法赫米回答的评论?如果我们把子查询放在select子句中,它也在Oracle中工作?那它有什么意义吗?我想不出来。@Sujitmohanty30。我不会把你的问题解释为如何写逻辑,尽管这回答了那个问题。我将其解释为您的代码无法工作的原因。答案似乎是Oracle中的一个bug。代码很好;据我所知,它适用于任何其他数据库。不,不,你误解了我。我不想回答,但我想问你的是……这对你有什么意义吗?当我输入select子句时,它就开始工作了。我自己也不知道,哪里需要你的投入。但无论如何,谢谢你的回复,底线是这似乎是错误。
select x.*
from (select region, sum(amount) as sm_amount, (select sum(amount)/3 from PLCH_SALES) as thirds
      from PLCH_SALES
      group by region
     ) x
where sm_amount > thirds ;
with thirds as (
      select sum(s2.amount)/3 as val from PLCH_SALES s2
     )
select region, sum(amount) sm_amount
from PLCH_SALES
group by region
having sum(amount) > (select val from thirds);