你必須使用pivot來完成這件事,但這不可能是動態的,你必須事先知道矩陣中的列。
下面的查詢適用於1到9之間的event_id,如果它更大,則將其相應地添加到select和pivot子句中。
declare @t table
(
hosts VARCHAR(20), event_id int
)
insert into @t values ('system1','1')
insert into @t values ('System2','1')
insert into @t values ('System1','2')
insert into @t values ('System3','1')
insert into @t values ('System2','2')
insert into @t values ('System3','4')
select * from @t
Select Hosts,[1],[2],[3],[4],[5],[6],[7],[8],[9]
from
(
select hosts,hosts as Hosts1,Event_id from @t
) P
pivot
(
count(Hosts1) for Event_id in ([1],[2],[3],[4],[5],[6],[7],[8],[9])
) as pvt
您可以瞭解更多關於支點從這裏http://msdn.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx
對於上述SQL實現動態支點
CREATE TABLE #t
(
hosts VARCHAR(20), event_id int
)
insert into #t values ('system1','1')
insert into #t values ('System2','1')
insert into #t values ('System1','2')
insert into #t values ('System3','1')
insert into #t values ('System2','2')
insert into #t values ('System3','4')
select * from #t
declare @sql varchar(4000)
declare @ColumnList VARCHAR(2000)
select @columnList = stuff((select ',[' + CAST(event_id AS VARCHAR) + ']' from (select distinct event_id from #t) a1 for xml path('')),1,1,'') -- get the concatenated list of the event_id columns seperated by a comma.
select @columnList
SET @sql =
'Select Hosts,' + @columnList + '
from
(
select hosts,hosts as Hosts1,Event_id from #t
) P
pivot
(
count(Hosts1) for Event_id in (' + @columnList + ')
) as pvt'
exec (@sql)
感謝您在R中發現,我想知道如何在SQL中完成。 – azzaxp
偏題:[SQLFiddle](http://sqlfiddle.com/)的C盤上的磁盤空間不足... –
您正在使用哪些DBMS? Postgres的?甲骨文? –