gpt4 book ai didi

sql - 将最小值/最大值与条件运算符一起使用

转载 作者:行者123 更新时间:2023-12-04 21:00:01 25 4
gpt4 key购买 nike

我正在尝试运行查询以查找最大值和最小值,然后使用条件运算符。但是,当我尝试运行以下查询时,它给了我错误 - “滥用聚合:min()”。

我的查询是:

SELECT a.prim_id, min(b.new_len*36) as min_new_len, max(b.new_len*36) as max_new_len
FROM tb_first a, tb_second b
WHERE a.sec_id = b.sec_id AND min_new_len > 1900 AND max_new_len < 75000
GROUP BY a.prim_id
ORDER BY avg(b.new_len*36);

有什么建议吗?

最佳答案

您需要使用 HAVING 子句按包含聚合的表达式进行过滤。

如果您使用的是 MySQL,则可以将该子句中的列别名用于您不能使用的其他 RDBMS。

SELECT a.prim_id,
min(b.new_len * 36) as min_new_len,
max(b.new_len * 36) as max_new_len
FROM tb_first a
JOIN tb_second b
ON a.sec_id = b.sec_id /*<-- Use explicit JOIN syntax...*/
GROUP BY a.prim_id
HAVING min(b.new_len * 36) > 1900
AND max(b.new_len * 36) < 75000
ORDER BY avg(b.new_len * 36);

在许多 RDBMS 中,您还可以将查询放入内联 View 并从中选择使用列别名而不是重复公式。在这种情况下,您确实会使用 WHERE,如下所示。

SELECT prim_id,
min_new_len,
max_new_len
from (SELECT a.prim_id,
min(b.new_len * 36) as min_new_len,
max(b.new_len * 36) as max_new_len,
avg(b.new_len * 36) as avg_new_len
FROM tb_first a
JOIN tb_second b
ON a.sec_id = b.sec_id
GROUP BY a.prim_id) derived
WHERE min_new_len > 1900
AND max_new_len < 75000
ORDER BY avg_new_len;

关于sql - 将最小值/最大值与条件运算符一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5148736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com