从表的两个选定列生成的矩阵视图

时间:2012-11-28 16:11:29

标签: sql database view pivot

假设我有一个包含Project_typeProject_NoOS_Platform列的表格。在这里,我有限制Project_type s和有限OS_Platform s。我想要一个数据库视图,它可以生成Project_typeOS_Platform之间的矩阵。

 MY_TABLE : 
 Project_Type     Project_No       OS_Platform 
 Drivers          345              Linux
 WebService       453              Windows                    
 Drivers          034              Windows            
 Drivers          953              Solaris
 DesktopApp       840              Windows 
 WebService       882              Solaris   

现在我已将Project_typeOS_Platform作为选定列。我想要一个具有不同行和列名称的这两列的矩阵视图。

Project_Type     Linux    Windows     Solaris
WebService       null      true         true
Drivers          true      true         true
DesktopApp       null      true         null

任何人都可以告诉我是否有可能。怎么可能?

3 个答案:

答案 0 :(得分:2)

这基本上是一个PIVOT查询,您可以将数据行转换为列。由于您需要true/null值,因此执行此操作的最简单方法是使用聚合函数和CASE语句:

select project_type,
  max(case when os_platform ='Linux' then 'true' else null end) Linux,
  max(case when os_platform ='Windows' then 'true' else null end) Windows,
  max(case when os_platform ='Solaris' then 'true' else null end) Solaris
from yourtable
group by project_type

请参阅SQL Fiddle with Demo

结果是:

| PROJECT_TYPE |  LINUX | WINDOWS | SOLARIS |
---------------------------------------------
|   DesktopApp | (null) |    true |  (null) |
|      Drivers |   true |    true |    true |
|   WebService | (null) |    true |    true |

答案 1 :(得分:1)

如果您正在使用的SQL产品支持,您也可以尝试使用专用的PIVOT功能。例如,以下would work in SQL Server 2005+

SELECT *
FROM (
  SELECT DISTINCT
    Project_Type,
    'true' AS flag,
    OS_Platform
  FROM MY_TABLE
) s
PIVOT (
  MAX(flag)
  FOR OS_Platform IN (
    Linux, Windows, Solaris
  )
) p
;

Oracle数据库是另一种支持PIVOT的产品,虽然我不确定它最初是在哪个版本中引入的。将PIVOT IN列表中的每一列用单引号括起来后,您就可以运行上面的查询in Oracle,如下所示:

... IN (
  'Linux', 'Windows', 'Solaris'
)
...

答案 2 :(得分:0)

您需要转动/取消转换您的值,以便将它们转换为您选择的格式。

这是一个谷歌搜索堆栈溢出的枢轴。任何这些都可以。 https://www.google.com/search?q=sql+pivot+unpivot+site%3Astackoverflow.com&oq=sql+pivot+unpivot+site%3Astackoverflow.com&aqs=chrome.0.57.9985&sugexp=chrome,mod=8&sourceid=chrome&ie=UTF-8

现在,你会看到两种类型的答案。第一种是常规的枢轴/单向操作。使用已知数据集,这些工作非常好(轻松,不快)。也就是说,如果您了解所有项目类型和平台,这将正常工作。

第二种类型是动态数据透视,或使用动态SQL创建的数据透视表。这比较麻烦,但允许你任意组合。

祝你好运!