SELECT 来自 table 类别的最小值和最大值

SELECT the Min & Max from a table with the category

我有一个包含多列的 table。我需要从整个 table 中获取最小值和最大值,还需要显示最小值和最大值所在的类别。我需要的列名是 Asset_Type 和 Asset_Value。有多种(5+)资产类型,但我只需要显示最小值和最大值的资产类型。

SELECT Asset_Type, MAX(Asset_Value), MIN(Asset_Value) 
FROM Asset
GROUP BY Asset_Type

这是我所拥有的,但这显示了每种资产类型的最小值和最大值,而不仅仅是 table 的最小值和最大值。

考虑到最大值可能与最小值有不同的Asset_type,你需要单独查询(这里没有考虑可能有多个Asset_type具有相同的min/max-value.

(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)

可以有多种具有最小值的资产类型和多种具有最大值的资产类型。所以简单地 select all 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;

还有其他方法可以编写此查询,但思路保持不变。