简体   繁体   中英

Matrix display from a SQL Server 2008 table

Does anyone know how to create a matrix display from a database table?
I'm using ASP.NET C# and the database is SQL Server 2008.

The table looks like this.

在此处输入图片说明

I would like the matrix to look like this or similar.

在此处输入图片说明

use 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

My suggestion here would be to pull the data out in exactly the format you have it, into a List of entities (at its simplest):

public class ServerApplicationRelationship
{
   public string Server{get;set;}
   public string Application{get;set;}
}

And create yourself a custom control which renders an HTML table using the List<ServerApplicationRelationship> as its datasource.

It should be pretty easy to render that table from the data provided.

If you really want to pull the data out in that shape from sql, you could use a query such as

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM