有一个表,关系为 Man(ID,Wife),其中的ID是唯一标示符,且一个ID对应的Wife可以有不同多个。表中的记录有很多,但是有的ID只对应一两个wife,而有的ID则对应几十个wife。问题是:能否把所有的记录排序,wife最少的ID记录排在所有记录的最上层,wife最多的ID排在最底部,即把每个 ID根据其wife的拥有量进行递增排序,并且group by ID。
排好后的结果即如下所示:
ID , wife
55 , Marry
12 , Rose
12 , Linda
07 , Linda
07 , Masa
07 , Jeccia
07 , O’neal
--生成测试数据
create table man(ID varchar(10),wife varchar(10))
insert into man select '12' ,'Rose'
insert into man select '07' ,'Masa'
insert into man select '07' ,'Jeccia'
insert into man select '12' ,'Linda'
insert into man select '07' ,'Linda'
insert into man select '55' ,'Marry'
insert into man select '07' ,'O’neal'
--执行查询
select
a.*
from
Man a,
(select ID,NUM=count(*) from Man GROUP BY ID) b
where
a.ID = b.ID
order by
b.NUM,a.ID,a.wife
--输出结果
ID wife
---- -------
55 Marry
12 Linda
12 Rose
07 Jeccia
07 Linda
07 Masa
07 O’neal
--建立测试环境
Create table man(ID Varchar(10),wife Varchar(10))
Insert into man Select '12' ,'Rose'
Insert into man Select '07' ,'Masa'
Insert into man Select '07' ,'Jeccia'
Insert into man Select '12' ,'Linda'
Insert into man Select '07' ,'Linda'
Insert into man Select '55' ,'Marry'
Insert into man Select '07' ,'O’neal'
--测试
Select * from Man A Order By (Select Count(1) from Man Where ID=A.ID),ID,wife
--删除测试环境
Drop Table Man
--结果
/*
IDwife
55Marry
12Linda
12Rose
07Jeccia
07Linda
07Masa
07O’neal
*/