Difference between revisions of "SELECT .. GROUP BY"

From SQLZOO
Jump to: navigation, search
Line 19: Line 19:
 
   name VARCHAR(20),
 
   name VARCHAR(20),
 
   date date);
 
   date date);
INSERT INTO games VALUES (1,'a','jan,10,2014');
+
INSERT INTO emp VALUES (1,'a','jan,10,2014');
INSERT INTO games VALUES (2,'b','jan,11,2014');
+
INSERT INTO emp VALUES (2,'b','jan,11,2014');
INSERT INTO games VALUES (3,'c','jan,10,2014');
+
INSERT INTO emp VALUES (3,'c','jan,10,2014');
INSERT INTO games VALUES (4,'d','jan,11,2014');
+
INSERT INTO emp 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:34, 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 emp VALUES (1,'a','jan,10,2014');
INSERT INTO emp VALUES (2,'b','jan,11,2014');
INSERT INTO emp VALUES (3,'c','jan,10,2014');
INSERT INTO emp 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