The syntax of the SELECT statement with the GROUP BY and HAVING clauses : Having « Query « SQL Server / T-SQL Tutorial






SELECT select_list
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_list]
[HAVING search_condition]
[ORDER BY order_by_list]

A summary query that calculates the average Billing amount by Banker
15>
16>
17> create table Billings (
18>     BankerID           INTEGER,
19>     BillingNumber      INTEGER,
20>     BillingDate        datetime,
21>     BillingTotal       INTEGER,
22>     TermsID            INTEGER,
23>     BillingDueDate     datetime ,
24>     PaymentTotal       INTEGER,
25>     CreditTotal        INTEGER
26>
27> );
28> GO
1>
2> INSERT INTO Billings VALUES (1, 1, '2005-01-22', 165, 1,'2005-04-22',123,321);
3> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (2, 2, '2001-02-21', 165, 1,'2002-02-22',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (3, 3, '2003-05-02', 165, 1,'2005-04-12',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (4, 4, '1999-03-12', 165, 1,'2005-04-18',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (5, 5, '2000-04-23', 165, 1,'2005-04-17',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (6, 6, '2001-06-14', 165, 1,'2005-04-18',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (7, 7, '2002-07-15', 165, 1,'2005-04-19',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (8, 8, '2003-08-16', 165, 1,'2005-04-20',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (9, 9, '2004-09-17', 165, 1,'2005-04-21',123,321);
2> GO

(1 rows affected)
1> INSERT INTO Billings VALUES (0, 0, '2005-10-18', 165, 1,'2005-04-22',123,321);
2> GO

(1 rows affected)
1>
2>
3>
4> SELECT BankerID, AVG(BillingTotal) AS AverageBillingAmount
5> FROM Billings
6> GROUP BY BankerID
7> HAVING AVG(BillingTotal) > 2000
8> ORDER BY AverageBillingAmount DESC
9> GO
BankerID    AverageBillingAmount
----------- --------------------

(0 rows affected)
1>
2>
3> drop table  Billings;
4> GO








1.5.Having
1.5.1.The syntax of the SELECT statement with the GROUP BY and HAVING clauses
1.5.2.HAVING clause defines the condition that is then applied to groups of rows.
1.5.3.The HAVING clause can also be used without aggregates.
1.5.4.Having and table join
1.5.5.A summary query with a search condition in the HAVING clause
1.5.6.A summary query with a compound condition in the HAVING clause
1.5.7.Selectively Query Grouped data using HAVING