0

我有一个“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,但如果那不可能, 我能理解...

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

4

1 回答 1

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
于 2013-02-15T05:57:24.997 回答