4

假设我有一个包含Project_type, Project_No,OS_Platform列的表。这里我有limited Project_types和limited OS_Platforms。Project_type我想要一个数据库视图,它在和之间产生一个矩阵OS_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

谁能告诉我是否可能。这怎么可能?

4

3 回答 3

2

如果您使用的 SQL 产品支持专用 PIVOT 功能,您也可以尝试使用它。例如,以下将在 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 列表中的每一列用单引号括起来后,您就可以在 Oracle中运行上述查询,如下所示:

... IN (
  'Linux', 'Windows', 'Solaris'
)
...
于 2012-11-30T23:49:42.143 回答
1

这基本上是一个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

结果是:

| PROJECT_TYPE |  LINUX | WINDOWS | SOLARIS |
---------------------------------------------
|   DesktopApp | (null) |    true |  (null) |
|      Drivers |   true |    true |    true |
|   WebService | (null) |    true |    true |
于 2012-11-30T13:57:58.147 回答
0

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

这是关于堆栈溢出的 google 搜索。任何这些都会对你很好。 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=铬&ie=UTF-8

现在,您将在那里看到两种类型的答案。第一个是常规的透视/反透视操作。这些对已知数据集工作得很好(很容易,但不快) 。也就是说,如果您了解所有项目类型和平台,这将正常工作。

第二种是动态枢轴,或使用动态 SQL 创建的枢轴。这比较麻烦,但允许您任意组合字段。

祝你好运!

于 2012-11-30T13:43:13.677 回答