日期:2014-05-18  浏览次数:20505 次

怎样把编码最大的找出来

有这样一张表前三位表示   家庭编码,后两位表示   成员序号,如下有四个家庭

编码             姓名         是否户主    
520101       张老大           是
520102       张老二           否
520103       张老三           否  

520201       李老大           是

520301       王老大           是

520401       赵大               是
520402       赵二               否

现在我要把农户中编码最大的找出来,四个家庭的结果如下
520103       张老三           否  
520201       李老大           是
520301       王老大           是
520402       赵二               否

------解决方案--------------------
create table T(编码 nvarchar(10),姓名 nvarchar(10),是否户主 nvarchar(10))
insert T select '520101 ', '张老大 ', '是 '
union all select '520102 ', '张老二 ', '否 '
union all select '520103 ', '张老三 ', '否 '
union all select '520201 ', '李老大 ', '是 '
union all select '520301 ', '王老大 ', '是 '
union all select '520401 ', '赵大 ', '是 '
union all select '520402 ', '赵二 ', '否 '

select * from T as tmp
where not exists(select 1 from T where left(编码,4)=left(tmp.编码,4) and right(编码,2)> right(tmp.编码,2))
------解决方案--------------------
select *
from 表名 as T
where 编码 = (select max(编码) from 表名 where left(编码,4)=left(T.编码,4))