2011-10-12 57 views
1

有誰知道如何從數據庫表創建矩陣顯示?
我使用ASP.NET C#和數據庫是SQL Server 2008.來自SQL Server 2008表的矩陣顯示

表看起來像這樣。

enter image description here

我想矩陣看起來像這樣或類似的。

enter image description here

+1

類似問題透視表: http://stackoverflow.com/questions/1069677/pivot-table-in-c –

回答

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 
1

使用TSQL樞

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 
+0

編輯處理任何數量的服務器和應用程序。您可以將它放入存儲過程,以便於在asp.net代碼中與您的asp.net代碼 –

+0

進行整合,您可以使用ado.net調用存儲過程GetPivotTable來獲取數據透視表。 –

+0

感謝您的回覆。兩者看起來很有趣因爲我之前沒有使用它們,所以我必須稍微查看數據透視表。 – RickBowden