假设有下表
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 @Tselect 1,'aa' union allselect 2,'bb' union allselect 3,'cc' union allselect 3,'c' union allselect 3,null union allselect 4,'dd' union allselect 5,null union allselect 6,'ee' union allselect 6,'e' union allselect 7,'ff' union allselect 7,'f' union allselect 7,null union allselect 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 aa2 bb3 cc4 dd5 6 ee7 ff8 gg*/