Difference between revisions of "SELECT .. GROUP BY"

From SQLZOO
Jump to: navigation, search
Line 15: Line 15:
 
<div class='params'>schema:scott</div>
 
<div class='params'>schema:scott</div>
 
<source lang=sql class='tidy'> DROP TABLE games</source>
 
<source lang=sql class='tidy'> DROP TABLE games</source>
<source lang=sql class='setup'> CREATE TABLE games(
+
<source lang=sql class='setup'> CREATE TABLE emp(
   yr INTEGER,
+
   id INTEGER,
   city VARCHAR(20),
+
   name VARCHAR(20),
   continent VARCHAR(20));
+
   date date);
INSERT INTO games VALUES (2000,'Sydney','Australasia');
+
INSERT INTO games VALUES (1,'a','jan,10,2014');
INSERT INTO games VALUES (2004,'Athens','Europe');
+
INSERT INTO games VALUES (2,'b','jan,11,2014');
INSERT INTO games VALUES (2008,'Beijing','Asia');
+
INSERT INTO games VALUES (3,'c','jan,10,2014');
INSERT INTO games VALUES (2012,'London','Europe');
+
INSERT INTO games VALUES (4,'d','jan,11,2014');
 
</source>
 
</source>
 
In a GROUP BY statement only <i>distinct</i> values are shown for the column in the GROUP BY.
 
In a GROUP BY statement only <i>distinct</i> values are shown for the column in the GROUP BY.

Revision as of 06:24, 24 March 2014

SELECT .. GROUP BY

Host cities and continents for the Olympics Games are stored in the table games. Notice that Europe appears in the table twice:

games
yrcitycontinent
2000SydneyAustralasia
2004AthensEurope
2008BeijingAsia
2012LondonEurope
schema:scott
 DROP TABLE games
 CREATE TABLE emp(
  id INTEGER,
  name VARCHAR(20),
  DATE DATE);
INSERT INTO games VALUES (1,'a','jan,10,2014');
INSERT INTO games VALUES (2,'b','jan,11,2014');
INSERT INTO games VALUES (3,'c','jan,10,2014');
INSERT INTO games VALUES (4,'d','jan,11,2014');

In a GROUP BY statement only distinct values are shown for the column in the GROUP BY. This example shows the continents hosting the Olympics with the count of the number of games held.

SELECT continent, COUNT(yr) FROM games
 GROUP BY continent

See also

Personal tools
Namespaces

Variants
Actions
Reference
Toolbox
Google AdSense