sql having 子句的问题
sql issue with having clause
我正在尝试查询每个型号及其最常用的内存配置。
Table:
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
当我尝试列出模型及其最常用的 ram 时遇到问题。
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
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
来实现您的需要。如果你需要在配置上有领带时获得 max
或 min
ram,你应该在模型上再有一个 group by
。
我想你要找的是:
SELECT model,ram FROM (SELECT model,ram,count(ram) AS config
FROM pc
GROUP BY model,ram)
WHERE config=max(config)
记录应已按您的子查询分组
一种方法是使用 window 函数:
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;
我正在尝试查询每个型号及其最常用的内存配置。
Table:
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
当我尝试列出模型及其最常用的 ram 时遇到问题。
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
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
来实现您的需要。如果你需要在配置上有领带时获得 max
或 min
ram,你应该在模型上再有一个 group by
。
我想你要找的是:
SELECT model,ram FROM (SELECT model,ram,count(ram) AS config
FROM pc
GROUP BY model,ram)
WHERE config=max(config)
记录应已按您的子查询分组
一种方法是使用 window 函数:
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;