Presentation is loading. Please wait.

Presentation is loading. Please wait.

Grouping Data Steve Perry

Similar presentations


Presentation on theme: "Grouping Data Steve Perry"— Presentation transcript:

1 Grouping Data Steve Perry Email: steveperrymail@yahoo.com

2 Grouping Data The GROUP BY clause allows the grouping of data Aggregate functions are most often used with the GROUP BY clause GROUP BY divides a table into sets, then Aggregate functions return summary values for those sets. 2

3 GROUP BY Syntax SELECT select_list FROM table_list [WHERE conditions] GROUP BY group_by_list; 3

4 Example SELECT pub_id, COUNT(title) FROM book GROUP BY pub_id; All items in the Select list that are not in the Group By list must generate a single value for each group 4

5 Groups within Groups You may nest Groups within other groups by separating the columns with commas Example: SELECT pub_id, type, COUNT(type) FROM book GROUP BY pub_id, type; 5

6 Restrictions Again: Each item in the SELECT list must produce a single value Wrong: SELECT pub_id, type, COUNT(type) FROM book GROUP BY pub_id; 6

7 NULLs and GROUPS NULLs never equal another NULL BUT... GROUP BY will create a separate group for the NULLs Think of it as a Group of Unknowns 7

8 GROUP BY with WHERE You can use the WHERE clause when grouping of a subset of rows. The WHERE clause acts first to find the rows you want Then the GROUP BY clause divides the rows into groups SELECT type, AVG(price) FROM book WHERE advance > 5000 GROUP BY type; 8

9 No WHERE Same statement, no WHERE SELECT type, AVG(price) FROM book GROUP BY type; NULL group returned [In the previous example, the WHERE clause eliminated the NULLs] 9

10 ORDER the GROUPS GROUP BY puts rows into sets, but doesn't put them in order. SELECT type, AVG(price) FROM book WHERE advance > 5000 GROUP BY type ORDER BY 2; 10

11 HAVING Clause HAVING is like a WHERE clause for a GROUP WHERE limits rows HAVING limits GROUPs 11

12 HAVING Syntax SELECT select_list FROM table_list [WHERE conditions] GROUP BY group_list [HAVING conditions]; 12

13 HAVING Aggregates The WHERE conditions apply before Aggregates are calculated Then the HAVING conditions apply after Aggregates are calculated 13

14 HAVING vs. WHERE WHERE comes after the FROM HAVING comes after the GROUP BY WHERE conditions cannot include Aggregates HAVING conditions almost always include Aggregates 14

15 Example SELECT type, count(*) FROM book GROUP BY type HAVING COUNT(*) > 1; NOTE: Cannot use WHERE instead of HAVING since WHERE does not allow Aggregates 15

16 HAVING Conditions You may use more than one condition on a HAVING clause SELECT pub_id, SUM(advance), AVG(price) FROM book GROUP BY pub_id HAVING SUM(advance) > 15000 AND AVG(price) 3; 16

17 Last Slide 17


Download ppt "Grouping Data Steve Perry"

Similar presentations


Ads by Google