习题三

        习题十三、COUNT(*) ... WHERE

combine COUNT(*) with WHERE to return thenumber of rows that matches the WHERE clause.

return the number of rows in friends_of_pickles where the species is a dog?

select count (*)

            from friends_of_pickles

                    where   species = 'dog';

Result:

count (*)

3

       习题十四、SUM

find the sum of a given value. 

 find the total num_books_read made by thisfamily?

 SELECT SUM(num_books_read)

FROM family_members;

Result:

SUM(num_books_read)

380

           习题十五、AVG

find the average of a given value. 

find the average num_books_read made by eachfamily member?

 select avg (num_books_read)

from family_members ;  

Result:

avg (num_books_read)

126.66666666666667


!!Note: 
- Because of the way computers handle numbers, averages will not always becompletely exact.
!!

         习题十六、MINMAX

find the maximum or minimum value of a table. 

find the least number of legs in a family member and find the highest num_books_read that afamily member makes?

SELECT MIN(num_legs)

FROM family_members; 


select max (num_books_read)

from family_members;

Result:

max (num_books_read)

200

          习题十七、GROUP BY

friends_of_pickles

id

name

gender

species

height_cm

1

Dave

male

human

180

2

Mary

female

human

160

3

Fry

male

cat

30

4

Leela

female

cat

25

5

Odie

male

dog

40

6

Jumpy

male

dog

35

7

Sneakers

male

dog

55

             use aggregate functions such as COUNT, SUM, AVG, MAX, and MINwith the GROUP BY clause. splitthe table into different piles based on the value of each row. 

SELECT COUNT(*), species

 FROMfriends_of_pickles

 GROUP BY species;

return the tallest height for each species? Remember toreturn the species name next to the height too, like in the example query.

 select max(height_cm ) ,species

from friends_of_pickles

group by species;

Result:

max(height_cm )

species

30

cat

55

dog

180

human

          习题十八、NESTED QUERIES

put a SQL query inside another SQL query. 

SELECT * FROM family_members

WHERE num_legs =

           (SELECT MIN(num_legs)

          FROM family_members); 

 return the family members that have thehighest num_books_read?

SELECT * from family_members

where num_books_read =

          (select max (num_books_read)

                      from family_members )
Result:

id

name

species

num_books_read

num_legs

1

Dave

human

200

2

Current tables3:

family_members

id

name

gender

species

favorite_book

1

Dave

male

human

To Kill a Mockingbird

2

Mary

female

human

Gone with the Wind

3

Pickles

male

dog

null




你可能感兴趣的:(SQL基础学习)