首页 > 解决方案 > SQL(MS Access):对于给定的记录,如何从给定的一组字段中查询前 5 个值?

问题描述

我有一个包含几十个字段的表,其中 18 个是具有不同整数值的字段。我想为给定记录提取具有最大值的五个字段的字段名称和相应值。我将使用下表作为示例,我只想查询给定记录的两个最大值。

Name, FigureA, FigureB, FigureC
John, 40,      73,      81
Luke, 35,      21,      65   

我想为约翰返回以下内容:

FigureB, 73
FigureC, 81

我已经做到了这一点:

sSQL = "Select t.* " & _
            "From (Select 'A' as [FigureA], FigureA " & _
                    "From Table) as t " & _
            "Union All " & _
           "Select t.* " & _
            "From (Select 'B' as [FigureB], FigureB " & _
                    "From Table) as t " & _
            "Union All " & _
           "Select t.* " & _
            "From (Select 'C' as [FigureC], FigureC " & _
                    "From Table) as t"

标签: sqlexcelvbams-access

解决方案


在 MS Access 中,这可能是最简单的union all

select top (5) *
from (select t.*
      from (select top (1) "field1" as colname, max(field1) as max_val
            from t
           ) as t
      union all
      select t.*
      from (select top (1) "field2" as colname, max(field2)
            from t
           ) as t
      union all
      . . . 
     ) as t
order by max_val desc;

某些版本的 MS Access 不支持union allfrom子句。该组件可能需要视图。


推荐阅读