我有一张像下面这样的表。
我想要单个查询中的最小、最大和平均成本产品的 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');
Run Code Online (Sandbox Code Playgroud)
输出:
Min 12
Max 5
Avg 2093
Run Code Online (Sandbox Code Playgroud)
我尝试过如下所示,但它不起作用。
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
Run Code Online (Sandbox Code Playgroud)
我该怎么做
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12276 次 |
| 最近记录: |