2012-11-28 86 views
4

假设我有一个包含Project_type,Project_No,OS_Platform列的表格。这里我限制了Project_type和限制OS_Platform。我想要一个在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 

任何人都可以告诉我,如果这是可能的。这怎么可能?

+0

通过“有限,”你的意思是,你知道每个接口的所有可能的值?如果是这样,这变得容易。 –

+0

是的所有可能的值都是已知的..但我不感兴趣的价值是不参与 – NPK

回答

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创建的数据透视表。这很麻烦,但允许你组合任何字段。

祝你好运!

2

这基本上是一个PIVOT查询,您将您的数据行转换为列。

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 | 
+0

thnx。它为我工作。 – NPK

+0

@ user1860322乐意提供帮助,如果任何答案对您有帮助,请务必通过左侧的复选标记进行接受。它可以帮助未来的访问者,并让你的代表接受。 – Taryn

1

您也可以尝试,因为你想有一个true/null值使用聚合函数和CASE声明最简单的方法来执行此如果您正在使用的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' 
) 
... 
+0

它工作正常,并能够了解新概念PIVOT。 Thnx很多。 – NPK