gpt4 book ai didi

mysql - 在 mysql 查询中使用最小值、最大值和平均值

转载 作者:可可西里 更新时间:2023-11-01 07:37:33 33 4
gpt4 key购买 nike

我有一个如下所示的表格。

我想在单个查询中获得最低、最高和平均成本产品的 product_id。

CREATE TABLE productlist(product_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
cost INT);

INSERT INTO productlist(cost)
VALUES('2450'),
('2200'),
('2580'),
('2405'),
('3500'),
('1500'),
('1800'),
('1520'),
('1740'),
('1940'),
('2940'),
('1250'),
('1290'),
('1390'),
('2900');

输出:

Min    12
Max 5
Avg 2093

我像下面这样尝试过,但它不起作用。

SELECT product_id, MIN(cost) as mincost
FROM productlist
GROUP BY product_id
ORDER BY mincost ASC
LIMIT 0,1
UNION
SELECT product_id, max(cost) as maxcost
FROM productlist
GROUP BY product_id
ORDER BY maxcost DESC
LIMIT 0,1

我应该怎么做

最佳答案

select 'Min', product_id 
from productlist
where cost = (select min(cost) from productlist)
UNION
select 'Max', product_id
from productlist
where cost = (select MAX(cost) from productlist)
UNION
select 'Avg', round(AVG(cost),0) as Avg
from productlist

关于mysql - 在 mysql 查询中使用最小值、最大值和平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14098746/

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