【问题标题】:SELECT the Min & Max from a table with the category从具有类别的表中选择最小值和最大值
【发布时间】:2018-08-24 12:36:31
【问题描述】:

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

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

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

【问题讨论】:

标签: mysql sql max min


【解决方案1】:

考虑到最大值可能与最小值具有不同的 Asset_type,您需要将其单独查询(此处不考虑可能存在多个具有相同 min/max-value 的 Asset_type。

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

【讨论】:

    【解决方案2】:

    可以有许多资产类型具有最小值,许多资产类型具有最大值。因此,只需选择值匹配最小值或最大值(您在子查询中查找)的所有资产类型:

    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;
    

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

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 2011-12-14
      • 2017-12-17
      • 2011-06-24
      • 2015-02-22
      • 1970-01-01
      • 2014-12-01
      • 2019-02-09
      • 2014-12-01
      相关资源
      最近更新 更多