【提问】行转列问题,再次整理
http://bbs.csdn.net/topics/390670237
人员拥有卡片表:B
人员Id 卡片号码 最后修改时间
1 01235 2013-12-12
1 0123456 2013-12-13
1 01234567 2013-12-12
2 02345 2013-12-12
2 023456 2013-12-12
.................................
需要以下结果:
人员Id 卡片1 卡片2 卡片3 卡片4 卡片5
1 0000001235 0000123456 0001234567 null null
2 0000002345 0000023456 null null null
..................................................................
说明:1、卡片号码唯一
2、行转列后的卡片1、卡片2...数据长度为10位。
3、行转列之后的列数(卡片1、卡片2...)固定为5个,如上面的结果表,超过5个的话从中取5条,
可以根据列最后修改时间来过滤,过滤掉后面新加的卡号。
[解决办法]
你改参数就可以了@id是保留多少行,这里是5,@date是删选时间
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-16 14:44:05
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
--Dec 28 2012 20:23:12
--Copyright (c) Microsoft Corporation
--Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go
create table [B]([人员Id] int,[卡片号码] varchar(8),[最后修改时间] datetime)
insert [B]
select 1,'01235','2013-12-12' union all
select 1,'0123456','2013-12-13' union all
select 1,'01234567','2013-12-12' union all
select 2,'02345','2013-12-12' union all
select 2,'023456','2013-12-12'
--------------开始查询--------------------------
DECLARE @date DATE
DECLARE @id INT
SET @id=5
SET @date='2013-12-12'
declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename('卡片'+CONVERT(VARCHAR(2),ROW_NUMBER()OVER(ORDER BY GETDATE())))+'=max(case when id='+quotename(id,'''')+' then [卡片号码] else NULL end)'
from (SELECT right('0000000000'+[卡片号码],10) [卡片号码],ROW_NUMBER()OVER(PARTITION BY [人员Id] ORDER BY [人员Id]) id FROM [B] WHERE [最后修改时间]<=@date ) B
WHERE id<=@id
group by id
exec('select [人员Id]'+@s+' from (SELECT [人员Id],right(''0000000000''+[卡片号码],10) [卡片号码],ROW_NUMBER()OVER(PARTITION BY [人员Id] ORDER BY [人员Id]) id FROM [B]) B group by [人员Id]')
/*
人员Id 卡片1 卡片2
----------- ------------------ ------------------
1 0000001235 0000123456
2 0000002345 0000023456
*/
--drop table b
create table b([人员Id] int,[卡片号码] varchar(8),[最后修改时间] datetime)
insert b
select 1,'01235','2013-12-12' union all
select 1,'0123456','2013-12-13' union all
select 1,'01234567','2013-12-12' union all
select 2,'02345','2013-12-12' union all
select 2,'023456','2013-12-12'
go
declare @sql nvarchar(max);
set @sql = '';
;with t
as
(
select number as rownum
from master..spt_values
where number >0
and type = 'P'
)
select
@sql = @sql + ',max(case when rownum = '+cast(rownum as varchar)+' then right(''000000''+卡片号码,10) else null end) as 卡片'+
cast(rownum as varchar)
from t
where rownum<= 5 --固定是5个卡号
select @sql = 'select 人员Id' + @sql +
' from (select *,
ROW_NUMBER() over(partition by 人员Id order by @@servername) as rownum
from B)t' +
' group by 人员Id'
--select @sql
exec(@sql)
/*
人员Id卡片1卡片2卡片3卡片4卡片5
1000000123500001234560001234567NULLNULL
200000023450000023456NULLNULLNULL
*/