我以前写过一个动态的,和你问题类似
if object_id('shiyan') is not null
drop table shiyan
go
create table shiyan(id varchar(3),kk varchar(3),t datetime,tt varchar(10))
insert into shiyan select '002','yy','2007-01-02','07:30:00'
insert into shiyan select '002','yy','2007-01-02','11:20:00'
insert into shiyan select '002','yy','2007-01-02','08:30:00'
insert into shiyan select '002','yy','2007-01-02','12:20:00'
insert into shiyan select '001','yy','2007-01-02','07:30:00'
insert into shiyan select '001','yy','2007-01-02','11:20:00'
insert into shiyan select '001','yy','2007-01-02','08:30:00'
insert into shiyan select '001','yy','2007-01-02','12:20:00'
select id,kk,convert(varchar(10),t,120) as t,convert(varchar(8),tt,108) as tt from shiyan
结果
id kk t tt
---- ---- ---------- --------
002 yy 2007-01-02 07:30:00
002 yy 2007-01-02 11:20:00
002 yy 2007-01-02 08:30:00
002 yy 2007-01-02 12:20:00
001 yy 2007-01-02 07:30:00
001 yy 2007-01-02 11:20:00
001 yy 2007-01-02 08:30:00
001 yy 2007-01-02 12:20:00
(所影响的行数为 8 行)
if object_id('sy') is not null
drop table sy
go
select *into sy from (
select bj=(select count(1) from shiyan where s.id=id and s.kk=kk and s.t=t and tt<=s.tt ),id,kk,convert(varchar(10),t,120) as t,convert(varchar(8),tt,108) as tt from shiyan s) m
select * from sy
结果
bj id kk t tt
----------- ---- ---- ---------- --------
1 002 yy 2007-01-02 07:30:00
3 002 yy 2007-01-02 11:20:00
2 002 yy 2007-01-02 08:30:00
4 002 yy 2007-01-02 12:20:00
1 001 yy 2007-01-02 07:30:00
3 001 yy 2007-01-02 11:20:00
2 001 yy 2007-01-02 08:30:00
4 001 yy 2007-01-02 12:20:00
(所影响的行数为 8 行)
alter table sy alter column bj varchar(20)
update sy set bj='time'+bj
select * from sy order by bj asc
结果
bj id kk t tt
-------------------- ---- ---- ---------- --------
time1 002 yy 2007-01-02 07:30:00
time1 001 yy 2007-01-02 07:30:00
time2 001 yy 2007-01-02 08:30:00
time2 002 yy 2007-01-02 08:30:00
time3 002 yy 2007-01-02 11:20:00
time3 001 yy 2007-01-02 11:20:00
time4 001 yy 2007-01-02 12:20:00
time4 002 yy 2007-01-02 12:20:00
(所影响的行数为 8 行)
declare @sql varchar(4000)
set @sql=' '
select @sql=@sql+','+quotename(bj,N'''')+'=max(case bj when '+quotename(bj,N'''')+' then tt else ''00:00'' end)' from sy group by bj
select @sql='select id,kk,t'+@sql+' from sy group by id,kk,t'
exec(@sql)
结果
id kk t time1 time2 time3 time4
---- ---- ---------- -------- -------- -------- --------
001 yy 2007-01-02 07:30:00 08:30:00 11:20:00 12:20:00
002 yy 2007-01-02 07:30:00 08:30:00 11:20:00 12:20:00