例题:(不介绍创建和插入)
star表
●查询每个组合的名称及其成员个数
select g.name,count(*) 成员个数
from star s,stargroup g
where s.gid = g.gid
group by g.name
如果不写where s.gid=g,gid会出现成员个数重复
●查询身高最高的团员姓名及其身高
重点:嵌套语句
select name,height from star
where height = (select max(height) from star)
●查询每个组合的名称,及其平均年龄
重点:year(getdate())
select g,name '团名',avg(year(getdate())-byear) '平均年龄'
from star s,stargroup g
where s.gid=g.gid
group by g.name
●查询团员的最高身高,最矮身高以及最高身高与最矮身高的身高差
select
(select max(height) from star)"最高’
(select min(height) from star)'最矮”
(select max(height) from star) -(select min(height) from star)最大身高差
●按照身高降序列出首尔出生的团员的姓名,所属团名,出生年份,身高
升序:ASC,降序:DESC
select s.name,g.name,byear,height
from star s,stargroup g
where s.gid=g.gid
and born='首尔'
order by 4 desc
●查询哪些国家或城市只出了一个团员
group...by...
select born'只有一个团员的国家或城市’
from star
group by born
having count(*)=1
●查询团员中不同姓及其人数
substring(name,1,1):截取第一个字
substring(name,1,2):截取第一个到第二个字
select substring (nane, 1, 1) '姓’,count
(*)'人数
from star
group by substring (name,1,1)
select substring(name,1,1)'姓’,count(*)'人数
from star
group by substring(name,1,1)
●查询姓’金‘的团员是姓’李‘的团员多少倍
like '金'
select
(select count(*) from star where name like'金%)"姓金的人数”
select count (*
from star where name like'李%”"姓李的人数”
select count (*)
from star where name like"金%’)/(select count(*)
from star where name
like'李%),姓金的人数是姓李的人数的倍数
●查询首尔出生的团员最少的组合名称
select top 1 gid
select name from stargroup
where gid in (select top 1 gid
from star
where born ='首尔
group by gid
order by
count(*))