mysql max(avg()),在mysql查询中使用min,max和avg

我有一张桌子如下.

我想在Single Query中获得最低,最高和平均成本产品的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,sql,mysqli

来源: https://codeday.me/bug/20190704/1372171.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值