繁体   English   中英

Oracle - 在有条款中分组

[英]Oracle - group by in having clause

我的查询看起来像这样

select f.entity, MAX(to_char(f.whencreated, 'MM/DD/YYYY HH24:MI:SS')) from fan f
group by f.entity
having MAX((f.whencreated)) >
(select MAX((b.endtime)) from brun b
where b.cny# = f.cny#
and b.entity = f.entity
group by b.entity, f.entity);

我收到错误

ORA-00979: not a GROUP BY expression

在这个查询中,我想 select f.entity 如果表 f 中该实体的 Max(whencreated) 大于表 brun 中同一实体的 MAX((b.endtime))。

表格如下所示:

台扇:

ENTITY      WHENCREATED

A           09/01/2020 12:34:00

A           10/01/2020 12:12:12

B           08/01/2020 12:34:00

B           10/01/2020 12:12:12

表烧:

ENTITY      ENDTIME

A           09/02/2020 12:34:00

A           09/04/2020 12:12:12

B           08/01/2020 12:34:00

B           11/01/2020 12:12:12

查询应该返回

A           10/01/2020 12:12:12

因为实体 A 的 max(brun.endtime) 是 09/04/2020 12:12:12,它小于实体 A 的 max(fan.whencreated),即 10/01/2020 12:12 :12。

我会尝试不同的方法:

with temp as
  (select 
     f.entity,
     max(f.whencreated) max_fwhen,
     max(b.endtime) max_bend
   from fan f join brun b on b.dny# = f.cny#
                         and b.entity = f.entity
   group by f.entity
  )
select entity
from temp
where max_fwhen > max_bend;
            

顺便说一句,不要 MAX 一个字符串; 我相信您想使用日期,而不是字符串。 你会得到意想不到的结果,例如 1920 年 8 月 25 日比 2021 年 2 月 12 日“更大”。

我认为错误的原因是您在HAVING子句中的子查询引用f.cny# 由于该列不在主查询的GROUP BY子句中,因此此时无法引用它。

我认为你需要澄清你想要达到的目标。 “同一实体”意味着entity列的值相同,仅此而已。

select f.entity 如果表 f 中该实体的 Max(whencreated) 大于 MAX((b.endtime))

那么,在加入之前聚合怎么样:

select f.entity
from (select f.entity, max(whencreated)as maxwc
      from fan f
      group by f.entity
     ) f join
     (select b.entity, max(b.endtime) as maxet
      from brun b
      group by b.entity
     ) b
     on f.entity = b.entity and f.maxwc > b.maxet

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM