27,579
社区成员
发帖
与我相关
我的任务
分享
create table tb(id号 int ,状态号 varchar(2),日期 datetime)
insert tb
select 1 ,'00','20110204' union all
select 1 ,'01','20110305' union all
select 1 ,'02','20110406' union all
select 2 ,'05','20110605' union all
select 2 ,'01','20110609'
--drop table tb
select id号,max(case when id=1 then 状态号 end) as 状态号1,
max(case when id=1 then 日期 end) as 日期1,
max(case when id=2 then 状态号 end) as 状态号2,
max(case when id=2 then 日期 end) as 日期2
from
(select id=row_number() over (partition by id号 order by 日期 desc),* from tb) a
where id <= 2
group by id号
drop table tb
/******************
id号 状态号1 日期1 状态号2 日期2
----------- ---- ----------------------- ---- -----------------------
1 02 2011-04-06 00:00:00.000 01 2011-03-05 00:00:00.000
2 01 2011-06-09 00:00:00.000 05 2011-06-05 00:00:00.000
警告: 聚合或其他 SET 操作消除了空值。
(2 行受影响)
create table tb(id号 int ,状态号 varchar(2),日期 datetime)
insert tb
select 1 ,'00','20110204' union all
select 1 ,'01','20110305' union all
select 1 ,'02','20110406' union all
select 2 ,'05','20110605' union all
select 2 ,'01','20110609'
--drop table tb
select a.id号,a.状态号 as 状态号1,a.日期 as 日期1,
b.状态号 as 状态号2,b.日期 as 日期2
from
(select id=row_number() over (order by getdate()),* from tb) a,
(select id=row_number() over (order by getdate()),* from tb) b
where a.id号=b.id号 and a.id<b.id
and a.id<>1 and b.id<>1
/*
id号 状态号1 日期1 状态号2 日期2
----------- ---- ----------------------- ---- -----------------------
1 01 2011-03-05 00:00:00.000 02 2011-04-06 00:00:00.000
2 05 2011-06-05 00:00:00.000 01 2011-06-09 00:00:00.000
(2 行受影响)
*/