我有一个多列的表。我需要从整个表中获取min和max值,但也需要显示该min和max值在哪个类别中。我需要的列名是Asset_Type和Asset_Value。有多种(5+)资产类型,但我只需要显示最小值和最大值的资产类型。
SELECT Asset_Type, MAX(Asset_Value), MIN(Asset_Value)
FROM Asset
GROUP BY Asset_Type
这就是我所拥有的,但是对于每种资产类型,这都是min和max,而不仅仅是表的min和max。
发布于 2018-03-15 16:08:09
考虑到max值可能具有与min值不同的Asset_type值,您需要将其单独查询(此处不考虑可能存在多个具有相同min/max值的Asset_types )。
(select 'max', Asset_Type, max(Asset_Value) as 'Asset_Value'
from Asset
group by Asset_Type
order by 3 desc
limit 1)
union all
(select 'min', Asset_Type, min(Asset_Value)
from Asset
group by Asset_Type
order by 3 asc
limit 1)
发布于 2018-03-15 16:15:16
可以有许多具有最小值的资产类型,还有许多具有最大值的资产类型。因此,只需选择值与最小值或最大值匹配的所有asset_types (在子查询中查找该值):
select distinct asset_value, asset_type
where asset_value = (select min(asset_value) from asset)
or asset_value = (select max(asset_value) from asset)
order by asset_value, asset_type;
编写此查询还有其他方法,但思路仍然相同。
https://stackoverflow.com/questions/49303879
复制相似问题