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

寻求最佳解决方案
sql   server中,有150万行数据,第一个字段ID都有1440行记录(对应的时间从00时00分开始),格式为:
如:

22,     2007-06-01   00:01:00.000,     0.3
22,     2007-06-01   00:02:00.000,     0.1
22,     2007-06-01   00:03:00.000,     0.0
22,     2007-06-01   00:04:00.000,     0.0
...................
23,     2007-06-01   00:01:00.000,     0.1
23,     2007-06-01   00:02:00.000,     0.2
23,     2007-06-01   00:03:00.000,     0.1

现在要转换成下面的格式:
22,   0.3   0.1   0.0   0.0   ...   ...
23,   0.1   0.2   0.1   ...   ...   ...
...   .......................
请问如何实现才是最佳方案?

------解决方案--------------------
--创建测试数据
create table tb(id int,mydate datetime,value decimal(18,1))
insert into tb values(22, '2007-06-01 00:01:00.000 ',0.3)
insert into tb values(22, '2007-06-01 00:02:00.000 ',0.1)
insert into tb values(22, '2007-06-01 00:03:00.000 ',0.0)
insert into tb values(22, '2007-06-01 00:04:00.000 ',0.0)
insert into tb values(22, '2007-06-01 00:05:00.000 ',0.0)
insert into tb values(22, '2007-06-01 00:06:00.000 ',0.0)
insert into tb values(22, '2007-06-01 01:01:00.000 ',0.3)
insert into tb values(22, '2007-06-01 01:02:00.000 ',0.1)
insert into tb values(22, '2007-06-01 01:03:00.000 ',0.0)
insert into tb values(22, '2007-06-01 01:04:00.000 ',0.0)
insert into tb values(22, '2007-06-01 01:05:00.000 ',0.0)
insert into tb values(22, '2007-06-01 01:06:00.000 ',0.0)
insert into tb values(23, '2007-06-01 00:01:00.000 ',0.1)
insert into tb values(23, '2007-06-01 00:02:00.000 ',0.2)
insert into tb values(23, '2007-06-01 00:03:00.000 ',0.1)
insert into tb values(23, '2007-06-01 00:04:00.000 ',0.0)
insert into tb values(23, '2007-06-01 00:05:00.000 ',0.0)
insert into tb values(23, '2007-06-01 00:06:00.000 ',0.0)
insert into tb values(23, '2007-06-01 01:01:00.000 ',0.1)
insert into tb values(23, '2007-06-01 01:02:00.000 ',0.2)
insert into tb values(23, '2007-06-01 01:03:00.000 ',0.1)
insert into tb values(23, '2007-06-01 01:04:00.000 ',0.0)
insert into tb values(23, '2007-06-01 01:05:00.000 ',0.0)
insert into tb values(23, '2007-06-01 01:06:00.000 ',0.0)
go

select id,convert(varchar(13),mydate,120) '日期+小时 ',
max(case when datepart(minute,mydate) = 0 then value end) '00 ',
max(case when datepart(minute,mydate) = 1 then value end) '01 ',
max(case when datepart(minute,mydate) = 2 then value end) '02 ',
max(case when datepart(minute,mydate) = 3 then value end) '03 ',
max(case when datepart(minute,mydate) = 4 then value end) '04 ',
max(case when datepart(minute,mydate) = 5 then value end) '05 ',
max(case when datepart(minute,mydate) = 6 then value end) '06 '
from tb
group by id,convert(varchar(13),mydate,120)

drop table tb

/*
id 日期+小时 00 01 02 03 04 05 06
----------- ------------- ---- -- --- --- --- -- --
22 2007-06-01 00 NULL .3 .1 .0 .0 .0 .0
23 2007-06-01 00 NULL .1 .2 .1 .0 .0 .0
22 2007-06-01 01 NULL .3 .1 .0 .0 .0 .0
23 2007-06-01 01 NULL .1 .2 .1 .0 .0 .0

(所影响的行数为 4 行)
*/