读书人

请问聚合查询中,字段长度最小的那条记

发布时间: 2012-01-20 18:53:53 作者: rapoo

请教聚合查询中,字段长度最小的那条记录,示例数据如下:
typeID, tyepname 表名:computerinfo
001 联想品牌笔记本
001 联系T23笔记本
001 联想笔记本
002 DELL台式电脑
002 DELL品牌电脑
002 台式电脑

1.要查询的结果是:
001 联想笔记本
002 台式电脑
查询条件: 根据 typeID 分组,typename 字段长度最小的那个.
我写的SQL语句为:
select typeID, min(typename) from computerinfo group by typeID
查询出来的结果中,typename 是根据拼音来的.
select typeID, min(len(typename)) from computerinfo group by typeID
可以把字段长度最小的查出来,但显示的是长度.有没有更好的方法来解决?

2.要查询出来的结果是:
001 笔记本
002 电脑
查询条件: 根据typeID 分组, typename 字段中,都连续出来的部分


[解决办法]

select * from computerinfo as A
where not exists(select 1 from computerinfo where typeID=A.typeID and len(tyepname) <len(A.tyepname))
[解决办法]
我利用表
select typeID,lent=min(len(typename))
into #abc
from computerinfo group by typeID

select t1.*from computerinfo t1, #abc t2
where t2.lent=len(typename) and t1.typeID=t2.typeID

读书人网 >SQL Server

热点推荐