【问题标题】:sql issue with having clause带有子句的sql问题
【发布时间】:2015-11-15 22:19:46
【问题描述】:

我正在尝试使用最常用的 ram 配置查找每个模型的查询。

表:

PC (code, model, speed, ram, hd, cd, price)

到目前为止,我能够列出每个型号的每个 ram 配置以及 ram 配置的使用次数。

select model, ram, max(config)
  from (select model,ram,count(ram) as config
          from pc 
         group by model, ram)
 group by model, ram

输出:

MODEL   RAM  MAX(CONFIG)
------- ---- -----------
1232    64   2
1232    32   2
1233    128  3
1121    128  3
1233    64   1
1260    32   1

当我尝试列出具有最常用内存的模型时遇到问题。

select model, ram
  from (select model, ram, count(ram) as config
          from pc 
         group by model, ram)
 group by model
having config = max(config);


Error : ORA-00979: not a GROUP BY expression

【问题讨论】:

    标签: sql oracle group-by having ora-00979


    【解决方案1】:
    with x as 
    (select model,ram,count(ram) as config
    from pc 
    group by model,ram)
    , y as 
    (select model, max(config) as mxconfig from x group by model)
    select x.model, x.ram --choose max(x.ram) or min(x.ram) in case of a tie and group by x.model
    from x join y on x.model = y.model and x.config = y.mxconfig
    

    此解决方案使用cte 来实现您所需要的。如果您需要在配置平局时获得maxmin ram,则您应该在模型上再添加一个group by

    【讨论】:

    • 给出错误:ORA-00942:表或视图不存在
    • 同样的错误。我正在执行“选择模型,max(ram) from (select model,ram,count(ram) as config from pc group by model,ram) t group by model with config = (select max(config) from t)”跨度>
    • 再次修改..试试这个。
    • 哇。这行得通。非常感谢vkp !!!您能否简要总结一下这个查询的作用?
    • 第一个cte x 与您的查询相同。第二个cte 使用 x 的结果并进行更多操作。最后,您使用 x 和 y 之类的表,加入它们并选择您需要的内容。
    【解决方案2】:

    我认为您正在寻找的是:

    SELECT model,ram FROM (SELECT model,ram,count(ram) AS config
    FROM pc 
    GROUP BY model,ram)
    WHERE config=max(config)
    

    记录应该已经按您的子查询分组

    【讨论】:

    • 给出错误:ORA-00934:此处不允许使用组功能
    【解决方案3】:

    一种方法是使用窗口函数:

    select model, ram
    from (select model, ram,
                 row_number() over (partition by model order by count(*) desc) as seqnum
          from pc 
          group by model, ram
         ) mr
    where seqnum = 1;
    

    【讨论】:

    • 这行得通。但是当 2 个 ram 配置被使用相同次数时会发生什么?会显示哪一个?
    • @zoro 。 . .将任意选择一个。如果两者都需要,请使用rank()dense_rank()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多