摘抄自论坛资源:http://topic.youkuaiyun.com/u/20080926/18/851a0827-25ab-43bb-b914-f30f753fdeaf.html
要求如下:
==============================================================
表的两个字段F1,F2,其值如下
F1 F2
01 a
01 aa
02 b
02 bb
02 bbb
现在想用SQL语句让上面的记录显示为
01 a
aa
02 b
bb
bbb
如何写?
==============================================================
实现:
- declare @t table(F1 varchar(8),F2 varchar(8))
- insert into @t values('01','a ')
- insert into @t values('01','aa ')
- insert into @t values('02','b ')
- insert into @t values('02','bb ')
- insert into @t values('02','bbb')
方法一:
- select
- (
- case
- when
- exists(select 1 from @t where F1=t.F1 and F2<t.F2) then ''
- else
- F1
- end
- ) as NewF1, F2
- from
- @t t
- order by
- F1,F2
方法二:
-
- select
- isnull(b.f1,'') f1,a.f2
- from
- @t a
- left join
- (select f1,min(f2) f2 from @t group by f1) b
- on a.f1=b.f1 and a.f2=b.f2
方法三:
- set nocount on;
- declare @T table([F1] nvarchar(2),[F2] nvarchar(3))
- Insert @T
- select N'01',N'a' union all
- select N'01',N'aa' union all
- select N'02',N'b' union all
- select N'02',N'bb' union all
- select N'02',N'bbb'
- Select [F1]=case when [F2]=(select top 1 [F2] from @T where [F1]=t.[F1]) then [F1] else '' end,
- [F2]
- from @T t
如果是SQL2005以上版本,则可使用如下方法:
- set nocount on;
- declare @T table([F1] nvarchar(2),[F2] nvarchar(3))
- Insert @T
- select N'01',N'aa' union all
- select N'01',N'aa' union all
- select N'02',N'bbb' union all
- select N'02',N'bbb' union all
- select N'02',N'bbb'union all
- select N'02',N'bbb'union all
- select N'02',N'bbb'
- select
- case when rowid = 1 then f1 else '' end as f1,
- f2
- from (
- select rowid = row_number() over(partition by f1 order by f1,f2) ,*
- from @t) a