【问题标题】:Oracle - group by in having clauseOracle - group by in having 子句
【发布时间】:2021-08-15 01:01:03
【问题描述】:

我的查询如下所示

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

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

表格如下所示:

桌扇:

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。

【问题讨论】:

  • 请提供样本数据、期望的结果以及清晰的逻辑解释。
  • 您的内部查询在实体上有一个组,而它们没有被选中。可能是因为这个?
  • 我添加了示例数据

标签: sql oracle group-by having-clause


【解决方案1】:

我会尝试不同的方法:

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 日“更大”。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我添加了数据和预期的结果。
    • @Jean OK - 您的示例数据根本不包括 cny# 列。为什么在查询中使用它?
    【解决方案3】:

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

    好吧,加入之前聚合怎么样:

    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
    

    【讨论】:

      猜你喜欢
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      相关资源
      最近更新 更多