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

求一条SQL语句,不知怎么解决
假设有下表

ID Description
1 aa
2 bb
3 cc
3 c
3  
4 dd
5  
6 ee
6 e
7 ff
7 f
7  
8 gg

相同ID有可能有不同描述(description),或者没有描述,
现在我想取出所有ID及其描述,如果描述有多种,取最详细的
那种(比如cc和C,就要取cc)。如果没有描述,这个id也要
取出,最后的结果应该是

ID Description
1 aa
2 bb
3 cc
4 dd
5  
6 ee
7 ff
8 gg


该怎样解决呢?谢谢

------解决方案--------------------
SQL code

declare @T table (ID int,Description varchar(2))
insert into @T
select 1,'aa' union all
select 2,'bb' union all
select 3,'cc' union all
select 3,'c' union all
select 3,null union all
select 4,'dd' union all
select 5,null union all
select 6,'ee' union all
select 6,'e' union all
select 7,'ff' union all
select 7,'f' union all
select 7,null union all
select 8,'gg'

select ID,Description=
isnull((select top 1 Description from @T where ID=t.ID order by len(Description) desc),'')
from @T t group by ID
/*
ID          Description
----------- -----------
1           aa
2           bb
3           cc
4           dd
5           
6           ee
7           ff
8           gg
*/