SQL Group By
Home
SQL Basics:
SQL HOME
SQL Introduction
SQL Select
SQL Where
SQL And & Or
SQL Between
SQL Distinct
SQL Order By
SQL Try It
SQL Insert
SQL Update
SQL Delete
SQL Count
SQL Advanced:
SQL Functions
SQL Group By
SQL Aliases
SQL Join
SQL Create
SQL Alter
SQL Quiz Test
Resources:
SQL Books
SQL Group By and Having
Aggregate functions (like SUM) often need an added GROUP BY
functionality.
The GROUP BY Keywords
The GROUP BY keywords have been added to SQL because aggregate functions
(like SUM) return the aggregate of all column values every time they are called.
Without the GROUP BY functionality, finding the sum for each individual group of
column values was not possible.
The syntax for the GROUP BY function is:
SELECT column,SUM(column) FROM table GROUP BY column
GROUP BY Example
This "Sales" Table:
Company
Amount
W3Schools
5500
IBM
4500
W3Schools
7100
And This SQL:
SELECT Company, SUM(Amount) FROM Sales
Returns this result:
Company
SUM(Amount)
W3Schools
17100
IBM
17100
W3Schools
17100
The above code is invalid because the column returned is not part of an
aggregate. A GROUP BY clause will correct, as in this SQL:
SELECT Company,SUM(Amount) FROM Sales
GROUP BY Company
Returns this result:
Company
SUM(Amount)
W3Schools
12600
IBM
4500
The HAVING Keyword
The HAVING keyword has been added to SQL because a WHERE keyword can not be used
against aggregate functions
(like SUM).
Without the HAVING keyword it would not be possible to test for function
result conditions.
The syntax for the HAVING function is:
SELECT column,SUM(column) FROM table
GROUP BY column
HAVING SUM(column) condition value
This "Sales" Table:
Company
Amount
W3Schools
5500
IBM
4500
W3Schools
7100
This SQL:
SELECT Company,SUM(Amount) FROM Sales
GROUP BY Company HAVING SUM(Amount)>10000
Returns this result
Company
SUM(Amount)
W3Schools
12600
Jump to : Top Of Page or HOME.
We Help you for free. Please Help us!
Help us correct errors
Help us with spelling and grammar
Tell us what you think
Link to us from your pages
All information in this Web is for training only. We do not make any warranties of its correctness or
its fitness to be used. The risk of using it remains with the user.
Copyright © 1999-2001 by Refsnes Data. All Rights Reserved.
More Tutorials:
HTML XHTML
XML XSL
CSS DTD
WAP WML
JavaScript
DHTML Flash
VBScript ASP
SQL AppML
News:
The Future ofProgramming
Web Security
Browser News
Web Standards
References:
HTML 4.01 Ref
XHTML 1.0 Ref
WML 1.1 Ref
CSS Reference
XSLT Elements
ASCII Reference
Entity Reference
HTML Colors
Color Values
Color Names
WAP Pages
Validation:
HTML XHTML
CSS DTD
XML WML
About W3Scripts
Please link to us
Larger Text?
XML Partners:
Wyszukiwarka
Podobne podstrony:
sql functions aspsql alter aspsql orderby aspsql alias aspsql create aspsql where aspsql quiz aspsql count aspsql select aspsql distinct aspsql insert aspsql join aspsql update aspsql intro aspsql tryit aspsql?lete aspsql and or aspsql framework aug94więcej podobnych podstron