Aggregate function in SQL WHERE-Clause

前端 未结 6 571
失恋的感觉
失恋的感觉 2020-11-27 15:22

In a test at university there was a question; is it possible to use an aggregate function in the SQL WHERE clause.

I always thought this isn\'t possibl

6条回答
  •  余生分开走
    2020-11-27 15:54

    You haven't mentioned the DBMS. Assuming you are using MS SQL-Server, I've found a T-SQL Error message that is self-explanatory:

    "An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference"

    http://www.sql-server-performance.com/


    And an example that it is possible in a subquery.

    Show all customers and smallest order for those who have 5 or more orders (and NULL for others):

    SELECT a.lastname
         , a.firstname
         , ( SELECT MIN( o.amount )
             FROM orders o
             WHERE a.customerid = o.customerid
               AND COUNT( a.customerid ) >= 5
            )
            AS smallestOrderAmount
    FROM account a
    GROUP BY a.customerid
           , a.lastname
           , a.firstname ;
    

    UPDATE.

    The above runs in both SQL-Server and MySQL but it doesn't return the result I expected. The next one is more close. I guess it has to do with that the field customerid, GROUPed BY and used in the query-subquery join is in the first case PRIMARY KEY of the outer table and in the second case it's not.

    Show all customer ids and number of orders for those who have 5 or more orders (and NULL for others):

    SELECT o.customerid
         , ( SELECT COUNT( o.customerid )
             FROM account a
             WHERE a.customerid = o.customerid
               AND COUNT( o.customerid ) >= 5
            )
            AS cnt
    FROM orders o
    GROUP BY o.customerid ;
    

提交回复
热议问题