Aggregate function in SQL WHERE-Clause

前端 未结 6 584
失恋的感觉
失恋的感觉 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:42

    Another solution is to Move the aggregate fuction to Scalar User Defined Function

    Create Your Function:

    CREATE FUNCTION getTotalSalesByProduct(@ProductName VARCHAR(500))
    RETURNS INT
    AS
    BEGIN
    
    DECLARE @TotalAmount INT
    
    SET @TotalAmount = (select SUM(SaleAmount) FROM Sales where Product=@ProductName)
    
    RETURN @TotalAmount
    
    END
    

    Use Function in Where Clause

    SELECT ProductName, SUM(SaleAmount) AS TotalSales
    FROM Sales
    WHERE dbo.getTotalSalesByProduct(ProductName)  > 1000
    GROUP BY Product
    

    References:

    1. 2.

    Hope helps someone.

提交回复
热议问题