簡體   English   中英

SQL Server 2008表中的矩陣顯示

[英]Matrix display from a SQL Server 2008 table

有誰知道如何從數據庫表創建矩陣顯示?
我正在使用ASP.NET C#,數據庫是SQL Server 2008。

該表如下所示。

在此處輸入圖片說明

我希望矩陣看起來像這樣或類似。

在此處輸入圖片說明

使用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

我的建議是將數據完全按照您擁有的格式提取到實體列表中(最簡單的方法):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM