如何使用SQL语句将数据从行记录转换为列记录

时间:2014-11-26 03:16:22

标签: c# sql sql-server

我想通过SQL语句将数据从行记录转换为列记录。数据库结构如下所示:

Table TestMethod是动态的。用户可以添加测试记录。

表TestMethod

ID, TestMethod
1, TestA
2, TestB
3, TestC
4, Test..
5, Test..
6, Test..

表A

ID, Code, TestMethod, RevNo, Value
1, A001, 1, 1, N
2, A002, 2, 1, N
3, A001, 3, 1, Y
4, A001, 1, 2, Y
...
...
...

如何通过SQL语句将数据转换为以下结构?

Code, RevNo, TESTA, TESTB, TESTC, TEST.., TEST.., TEST..
A001, 1, N, null, Y
A002, 1, null, N, null
A001, 2, Y, null, null

请向我提出一些解决方案,谢谢。

1 个答案:

答案 0 :(得分:2)

以下是使用交叉表进行此操作的一种方法:

use tempdb
create table temp(
    id int,
    Code varchar(10),
    TestMethod varchar(10),
    RevNo int,
    Value varchar(10)
)
insert into temp values
(1, 'A001', 'TESTA', 1, 'N'),
(2, 'A002', 'TESTB', 1, 'N'),
(3, 'A001', 'TESTC', 1, 'Y'),
(4, 'A001', 'TESTA', 2, 'Y')

select
    Code,
    RevNo,
    TestA = max(case when TestMethod = 'TESTA' then value end),
    TestB = max(case when TestMethod = 'TESTB' then value end),
    TestC = max(case when TestMethod = 'TESTC' then value end)
from temp
group by
    Code,
    revno

drop table temp

更新:使用动态交叉标签

use tempdb
create table TestMethod(
    Id int,
    TestMethod varchar(10)
)
create table TableA(
    Id int,
    Code varchar(10),
    TestMethodId int,
    RevNo int,
    Value varchar(10)
)
insert into TableA values
(1, 'A001', '1', 1, 'N'),
(2, 'A002', '2', 1, 'N'),
(3, 'A001', '3', 1, 'Y'),
(4, 'A001', '1', 2, 'Y'),
(5, 'A001', '2', 2, 'Y'),
(6, 'A002', '4', 1, 'Y'),
(7, 'A002', '5', 1, 'Y')
insert into TestMethod values
(1, 'TestA'),
(2, 'TestB'),
(3, 'TestC'),
(4, 'TestD'),
(5, 'TestE')

declare @sql1 varchar(4000) = ''
declare @sql2 varchar(4000) = ''
declare @sql3 varchar(4000) = ''

select @sql1 = 
'select
    a.Code
    ,a.RevNo
'
select @sql2 = @sql2 + 
'   ,max(case when a.TestMethodId  = ' + convert(varchar(10), Id) + ' then a.Value end) as [' + TestMethod + ']' + char(10)
from TestMethod 
order by TestMethod

select @sql3 = 
'from TableA a
inner join TestMethod m
    on m.id = a.TestMethodId
group by
    a.Code,
    a.RevNo
'

print (@sql1 + @sql2 + @sql3)
exec (@sql1 + @sql2 + @sql3)

drop table TestMethod
drop table TableA