转群友一个关于显示了分组方式下问题!!!!

/*--------------------- 建立测试表-----------------------------------------------------------------------------------*/
CREATE   TABLE   [ tx ]  (
                
[ name ]   [ char ]  ( 2 ) COLLATE Chinese_PRC_CI_AS  NULL  ,
                
[ num ]   [ int ]   NULL  ,
                
[ col ]   [ char ]  ( 2 ) COLLATE Chinese_PRC_CI_AS  NULL  
ON   [ PRIMARY ]
GO
/*--------------------插入记录-------------------------------------------------------------------------------------------*/
insert  tx
select   ' z ' , 1 , ' z1 '   union   all
select   ' z ' , 2 , ' z2 '   union   all
select   ' x ' , 1 , ' x1 '   union   all
select   ' x ' , 2 , ' x2 '   union   all
select   ' z ' , 2 , ' z1 '   union   all
select   ' z ' , 1 , ' z2 '   union   all
go
/*--------------------显示出以 以name分组下,num 最大或最小的记录集----------------------------*/
select  a. *
from  tx a ,( select  name, max (num)   as  num  from  tx  group   by  name)  as  b  -- --------一个表和一个表的条件子集匹配
where  a.name = b.name  and   a.num = b.num  -- ------以上二者的条件
--
-----------------------------------------------------------
1 ,num可变成比较大小的任意数据类型如:  datetime

 朋友的方法:

 

declare   @t   table (name  varchar ( 10 ),num  int ,col  varchar ( 10 ))
insert   into   @t   select   ' z ' , 1 , ' z1 '
union   all   select   ' z ' , 2 , ' z2 '
union   all   select   ' x ' , 3 , ' x1 '
union   all   select   ' x ' , 9 , ' x2 '
union   all   select   ' e ' , 4 , ' e1 '
union   all   select   ' e ' , 15 , ' e2 '

select   *
from   @t  a 
where   exists   -- ------exists的应用
             ( select   1   from   @t   where  a.name = name  group   by  name  having  a.num = max (num)) -- -------having a.num=max(num),只找出分组中最大num记录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值