SELECT 强查询

有一个表,关系为 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
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值