有谁知道如何从数据库表创建矩阵显示? 我正在使用ASP.NET C#,数据库是SQL Server 2008。
表格如下所示。
我希望矩阵看起来像这样或类似。
答案 0 :(得分:1)
使用TSQL pivot
create table table1
(
serverName varchar(30),
app varchar(50)
);
go
insert table1 (serverName , app) values ('server1' , 'app A');
insert table1 (serverName , app) values ('server2' , 'app A');
insert table1 (serverName , app) values ('server2' , 'app B');
insert table1 (serverName , app) values ('server3' , 'app B');
insert table1 (serverName , app) values ('server1' , 'app C');
insert table1 (serverName , app) values ('server3' , 'app C');
go
create procedure GetPivotTable
as begin
DECLARE @PivotColumnHeaders VARCHAR(MAX)
SELECT @PivotColumnHeaders =
COALESCE(@PivotColumnHeaders + ',[' + cast(t.serverName as varchar) + ']' ,
'[' + cast(t.serverName as varchar)+ ']')
FROM (select distinct serverName from table1) t
DECLARE @PivotTableSQL NVARCHAR(MAX)
SET @PivotTableSQL = N'
select * from
(select app, serverName from table1) sourceTable
pivot
(
count(serverName) for serverName in (' + @PivotColumnHeaders + ')
) pivottable
'
EXECUTE(@PivotTableSQL)
end
go
exec GetPivotTable
答案 1 :(得分:0)
我的建议是将数据完全以您拥有的格式提取到实体列表中(最简单):
public class ServerApplicationRelationship
{
public string Server{get;set;}
public string Application{get;set;}
}
创建一个自定义控件,使用List<ServerApplicationRelationship>
作为数据源呈现HTML表。
从提供的数据中渲染该表应该非常容易。
如果确实希望从sql中提取该数据,您可以使用
之类的查询select application,
case when exists(select 1 from example where application=ex.application and server='server 1') THEN 1 ELSE 0 end as [server 1],
case when exists(select 1 from example where application=ex.application and server='server 2') THEN 1 ELSE 0 end as [server 2],
case when exists(select 1 from example where application=ex.application and server='server 3') THEN 1 ELSE 0 end as [server 3]
from yourTable ex
group by application