使用数据透视表生成“训练矩阵”

时间:2013-02-15 04:09:26

标签: sql-server pivot

我有一张“CertificateEntries”表,其中包含;

Entity_ID | Certificate_ID | CertificateExpiry
1         | 1              | dd/mm/YYYY
1         | 2              | dd/mm/YYYY

等等。它本质上是一个多对多的关系,实体可以有许多证书,证书可以分配给许多实体。

我想要做的是将其旋转,以便证书列表是列;

Entity_ID | 1 | 2 | 3 | 4 |
1         | T | T | F | F |
2         | T | F | F | T |

我无法完全理解如何完成这项工作,所有在线示例似乎都表明您需要COUNT,MAX,AVG等。理想情况下,我希望能够在T / F代替到期但是如果那是不可能的,我能理解......

如果有人可以帮助我指出正确的方向,那就太棒了。感谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

begin try
create table #test 
(Entity_ID int,Certificate_ID int,CertificateExpiry date)

insert into #test values(1,1,'01/01/2013')
insert into #test values(1,2,'05/01/2013')
insert into #test values(1,5,'01/05/2013')
insert into #test values(1,9,'05/12/2013')

insert into #test values(2,1,'10/05/2013')
insert into #test values(2,2,'12/03/2013')
insert into #test values(4,6,'2/05/2013')
insert into #test values(5,8,'4/09/2013')

--select * from #test

DECLARE @Certificate_Ids VARCHAR(8000)


SELECT @Certificate_Ids = COALESCE(@Certificate_Ids + '], [', '') + cast(Certificate_ID as varchar(20)) FROM 
(select distinct Certificate_ID from #test ) as a


Set @Certificate_Ids='['+@Certificate_Ids+']'

--print @Certificate_Ids


Declare @query varchar(max)


Set @query=
'SELECT
Entity_ID, ' + @Certificate_Ids + ' 
FROM #test
PIVOT
(
  MAX(CertificateExpiry)
  FOR Certificate_ID in (' + @Certificate_Ids + ' )   
) A'

print @query

exec(@query)


drop table #test
end try

begin catch
drop table #test
end catch