【提问】行转列问题,重新整理
前面一帖,需求搞错,现在重新来一帖。
人员拥有卡片表:B
人员Id 卡片号码
1 01235
1 0123456
1 01234567
2 02345
2 023456
.................
需要以下结果:
人员Id 卡片1 卡片2 卡片3 卡片4 .... 卡片N
1 0000001235 0000123456 0001234567 null null ...
2 0000002345 0000023456 null null null ..
.............................................................................
说明:1、卡片号码唯一
2、行转列后的卡片1、卡片2...数据长度为10位。
[解决办法]
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-16 12:33:35
-- 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))
insert [B]
select 1,'01235' union all
select 1,'0123456' union all
select 1,'01234567' union all
select 2,'02345' union all
select 2,'023456'
--------------开始查询--------------------------
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]) B 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 卡片3
----------- ------------------ ------------------ ------------------
1 0000001235 0000123456 0001234567
2 0000002345 0000023456 NULL
*/
create table B(人员Id int, 卡片号码 varchar(10))
insert into b
select 1 ,'01235' union all
select 1 ,'0123456' union all
select 1 ,'01234567' union all
select 2 ,'02345' union all
select 2 ,'023456'
go
declare @sql nvarchar(max);
set @sql = '';
;with t
as
(
select *,
ROW_NUMBER() over(partition by 人员Id order by @@servername) as rownum
from B
)
select
@sql = @sql + ',max(case when rownum = '+cast(rownum as varchar)+' then 卡片号码 else null end) as 卡片'+
cast(rownum as varchar)
from t
group by rownum
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
101235012345601234567
202345023456NULL
*/