【问题标题】:Converting a table to matrix of 0's and 1's将表格转换为 0 和 1 的矩阵
【发布时间】:2013-07-04 15:19:41
【问题描述】:

我有一个主机和事件 ID 的表

Hosts     |   Event_id
system1          1
System2          1
System1          2
System3          1
System2          2

等等

现在我想把它们转换成一个矩阵

             |  1    2    3    4    5    6    7    8    9 ....
---------------------------------------------------------------------
    System1  |  1    1    0    1    1    0    1    0    0 ....
    System2  |  1    1    1    1    1    0    1    0    0 ....
    System3  |  1    0    0    1    1    0    1    0    0 ....

如何在 SQL 中做到这一点?

【问题讨论】:

  • 感谢您在 R 中发现这一点,我想知道如何在 SQL 中进行操作。
  • 离题:SQLFiddle 已用完 C 盘上的磁盘空间...
  • 您使用的是哪个 DBMS?后格雷斯?甲骨文?
  • 我有 MySQL 和 Oracle
  • 我在这里得到了答案。 stackoverflow.com/questions/13074319/…

标签: mysql sql oracle


【解决方案1】:

您必须使用 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了解更多关于pivot的信息

上述sql的动态pivot实现

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)

【讨论】:

  • 感谢 Surendra,但我不确定 Event_id。
  • 那么您必须使用动态枢轴,在此之前,请在您的系统中检查上述查询并让我知道它有效,然后我们可以使用动态枢轴解决方案。
  • 我没有 sql server,所以在 Mysql 中尝试了它对我有用。我有 CSV 格式的数据
  • 我没有mysql知识,上面的解决方案是编辑在sql server中运行的,在此基础上看看是否可以在mysql中完成。
【解决方案2】:

虽然可以动态构建枢轴,但通常在应用程序级别处理显示逻辑(例如使用简单的 PHP 循环)更容易、更灵活

【讨论】:

  • 你能分享一下怎么做吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多