【问题标题】:How do I create a query displaying only the rows with greatest and least values in Microsoft Access? 2010/2013如何在 Microsoft Access 中创建仅显示具有最大值和最小值的行的查询? 2010/2013
【发布时间】:2015-06-25 00:55:26
【问题描述】:

这是我所在的位置: SELECT Client.[First Name]、Client.[Last Name]、Client.Balance 来自客户 ORDER BY Client.Balance DESC;

我想找到一种方法,仅在第一行显示具有最大余额的客户,在第二行显示具有最小余额的客户。我尝试过使用 SQL 命令,但我对它很陌生,所以我不确定要输入的正确命令。到目前为止,我还没有遇到过这样做的方法,也没有人可以给我一个直接的答案。我已经上传了原始数据表herethis 是我想要的最终结果。如果有人有任何建议或替代方案,那就太好了。感谢您的宝贵时间。

【问题讨论】:

    标签: sql ms-access syntax syntax-error ms-access-2010


    【解决方案1】:

    考虑三种方法:

    使用 WHERE 子查询(可与 DMax()/DMin() 互换):

    SELECT Client.[First Name], Client.[Last Name], Client.Balance 
    FROM Client 
    WHERE Client.Balance 
       IN (SELECT Max(Client.Balance) FROM Client)
    OR Client.Balance 
       IN (SELECT Min(Client.Balance) FROM Client)
    ORDER BY Client.Balance DESC
    

    使用 Group By HAVING 子查询(可与 DMax()/DMin() 互换):

    SELECT Client.[First Name], Client.[Last Name], Client.Balance
    FROM Client
    GROUP BY Client.[First Name], Client.[Last Name], Client.Balance
    HAVING Max(Client.Balance) 
       IN (SELECT Max(Client.Balance) FROM Client)    
    OR Min(Client.Balance) 
       IN (SELECT Min(Client.Balance) FROM Client)
    

    使用 Union 和 Top 1 子句:

    (SELECT TOP 1 Client.[First Name], Client.[Last Name], Client.Balance
    FROM Client
    ORDER BY Client.Balance DESC)
    UNION 
    (SELECT TOP 1 Client.[First Name], Client.[Last Name], Client.Balance
    FROM Client
    ORDER BY Client.Balance ASC)
    

    【讨论】:

      【解决方案2】:

      这应该做你想做的:

      (SELECT Client.[First Name], Client.[Last Name], Client.Balance
       FROM Client
       ORDER BY Client.Balance DESC, Client.[Last Name]
      ) UNION ALL
      (SELECT Client.[First Name], Client.[Last Name], Client.Balance
       FROM Client
       ORDER BY Client.Balance ASC, Client.[Last Name]
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-03
        • 1970-01-01
        • 1970-01-01
        • 2023-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多