所以我有这个sql代码:
select stone_number,stone_size,stone_shape,stone_weight
from stone
left Join stone_price stp on stp.id_stone = stone.id_stone
group by stone_number,stone_size,stone_shape,stone_weight
having avg(stp.price) < stp.price;
Sqldeveloper返回:不是表达式的组我仍然在我的代码中有group by。 我的目标是得到价格高于所有宝石平均价格的石材。
答案 0 :(得分:1)
select stone_number, stone_size, stone_shape, stone_weight
from stone
left Join stone_price stp on stp.id_stone = stone.id_stone
group by stone_number, stone_size, stone_shape, stone_weight
having (select avg(price) from stone_price) < max(stp.price)
您需要在having
子句中的所有列上使用聚合函数。因此,如果您想获得至少一个奖品高于平均水平的宝石,您可以使用max()
。如果所有都需要更高,请使用min()
。
答案 1 :(得分:1)
您可以使用窗口功能执行此操作:
select *
from (
select stone_number,stone_size,stone_shape,stone_weight,
stp.price,
avg(stp.price) over () as avg_price
from stone
left Join stone_price stp on stp.id_stone = stone.id_stone
)
where price > avg_price;
请注意,外连接表上的条件实际上将外连接转换为内连接。如果您还希望在stone_price
中包含您需要
where price is null
or price > avg_price;
否则,您只需将left join
更改为“普通”join
另一个选项是简单的子选择:
select stone_number,stone_size,stone_shape,stone_weight,
from stone
left Join stone_price stp on stp.id_stone = stone.id_stone
where stp.price > (select avg(price) from stone_price);
答案 2 :(得分:0)
一种方法是使用存储过程,您可以设置如下变量:
DECLARE @average_price INT
SET @average_price = (SELECT Avg(stone_price) from stone
然后在SELECT语句中
select stone_number,stone_size,stone_shape,stone_weight
from stone
left Join stone_price stp on stp.id_stone = stone.id_stone
WHERE stone_price > @average_price