Microsoft SQL Server 2005
Advanced SQL Best Practices

How to use HAVING with the GROUP BY clause?

Execute the following script in Query Editor to demonstrate the usage of HAVING clause following a GROUP BY clause.

USE AdventureWorks;

GO

SELECT sod.SalesOrderID AS OrderID,

       convert(char(10),soh.OrderDate,110) AS "Date of Order",

       SUM(sod.OrderQty) AS "Units Sold",

       '$'+convert(varchar,SUM(sod.UnitPrice * sod.OrderQty),1)

       AS "Big Ticket Revenue"

FROM Sales.SalesOrderDetail AS sod

INNER JOIN Sales.SalesOrderHeader soh

ON soh.SalesOrderID=sod.SalesOrderID

WHERE sod.SalesOrderID

in (SELECT OrdD2.SalesOrderID

    FROM Sales.SalesOrderDetail AS OrdD2

    WHERE OrdD2.UnitPrice > $500)

GROUP BY sod.SalesOrderID, soh.OrderDate

HAVING SUM(sod.OrderQty) > 10

ORDER BY "Date of Order"

GO

 

 

The Best SQL Server 2005 Training in the World
 
 
SQLUSA.com Home Page