SQL问题:有Tabel T(c1 int, c2 nvarchar(50), c3 int)
c1 c2 c3
1 How 1
2 are 1
3 you 1
4 Fine 2
5 thanks 2
6 And 2
7 you 2
8 I 3
9 am 3
10 fine 3
11 too 3
想得到如下结果:
How are you
Fine thanks And you
I am fine too
以上问题如果用游标,临时表等等来实现,那是相当简单,但是游标和临时表都太占用资源,浪费性能,其实可以用简单的SQL语句来实现,完整的例子如下(SQL Server 2005实现):
1
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T]') AND type in (N'U'))
2
DROP TABLE [dbo].[T]
3
GO
4
5
create table T(
6
c1 int not null,
7
c2 nvarchar(50) not null,
8
c3 int not null
9
)
10
GO
11
12
insert into T(c1, c2, c3)
13
select 1, 'How', 1 union
14
select 2, 'are', 1 union
15
select 3, 'you', 1 union
16
select 4, 'Fine', 2 union
17
select 5, 'thanks', 2 union
18
select 6, 'And', 2 union
19
select 7, 'you', 2 union
20
select 8, 'I', 3 union
21
select 9, 'am', 3 union
22
select 10, 'fine', 3 union
23
select 11, 'too', 3
24
GO
25
26
declare @s nvarchar(300), @idx int
27
set @s=''
28
set @idx=0 -- 可以为任何值
29
30
select @s=@s
31
+ case @idx when c3 then ' ' else char(10) end
32
+ c2,
33
@idx = c3
34
from T
35
36
set @s=stuff(@s, 1, 1, '') -- 去@s首字符,为' '或为char(10)
37
print @s -- 打印查看结果
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37