纵转横,新问题。
以下分别为编号是员工9001、9002借还书的纪录:
sNo borrow repay odate
---------- ----------- ----------- -----------------------
9001 10 1 2006-01-01 00:00:00.000
9001 12 2 2006-01-02 00:00:00.000
9001 13 3 2006-01-03 00:00:00.000
9002 18 7 2006-01-01 00:00:00.000
9002 19 8 2006-01-02 00:00:00.000
9002 20 9 2006-01-03 00:00:00.000
现在想将这些数据转为横向显示,即:
sNo 2006-01-01 2006-01-02 2006-01-03
9001 10 12 13 --9001 's borrow
9001 1 2 3 --9001 's repay
9002 18 19 20 --9002 's borrow
9002 7 8 9 --9002 's repay
请大家帮忙看看,测试数据如下:
create table #
(
sNo varchar(10),
borrow int,
repay int,
odate datetime
)
insert into #
select '9001 ', 10, 1, '2006-01-01 ' union all
select '9001 ', 12, 2, '2006-01-02 ' union all
select '9001 ', 13, 3, '2006-01-03 ' union all
select '9002 ', 18, 7, '2006-01-01 ' union all
select '9002 ', 19, 8, '2006-01-02 ' union all
select '9002 ', 20, 9, '2006-01-03 '
select * from #
------解决方案--------------------create table test(sNo int,borrow int,repay int,odate datetime)
insert into test select 9001,10,1, '2006-01-01 00:00:00.000 '
insert into test select 9001,12,2, '2006-01-02 00:00:00.000 '
insert into test select 9001,13,3, '2006-01-03 00:00:00.000 '
insert into test select 9002,18,7, '2006-01-01 00:00:00.000 '
insert into test select 9002,19,8, '2006-01-02 00:00:00.000 '
insert into test select 9002,20,9, '2006-01-03 00:00:00.000 '
declare @sql1 varchar(8000),@sql2 varchar(8000)
set @sql1= ' '
set @sql2= ' '
select @sql1=@sql1+ ',[ '+odate+ ']=sum(case whe